0

Is it possible to make a UniqueConstraint using the field of a foreignkey model?

For example, how could I constrain all books written by authors of the same age to have a unique title? (A contrived example, but you get the idea.)

models.py:

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

class Book(models.Model):
    class Meta:
        contraints = [
            models.UniqueConstraint(
                # THIS DOESN'T WORK
                fields=["author__age", "title"],
                name="my_constraint",
            )
        ]
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name="books")

This gives the following error:

django.core.exceptions.FieldDoesNotExist: Book has no field named 'author__age

'

trubliphone
  • 4,132
  • 3
  • 42
  • 66

1 Answers1

3

No, UniqueConstraint doesn't work like that yet. See this answer for possible alternatives.

schillingt
  • 13,493
  • 2
  • 32
  • 34
  • Thank you. That helps. In my real code, `author.age` is actually another foreignkey, so I just setup a `UniqueConstraint` on that model. – trubliphone Mar 19 '20 at 18:04