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
'