pythondjangodjango-models

How to use Django generated fields to get a single value from a many-to-many relationship?


I have a Django model representing a Book, which can have many different types of Person, including AUTHOR, EDITOR, ILLUSTRATOR, etc.

class PersonType(models.Model):
    name = models.CharField()

class Person(models.Model):
    name = models.TextField()

class Book(models.Model):
    title = models.TextField()
    people = models.ManyToManyField(Person, through="PersonBook")

class PersonBook(models.Model):
    person_type = models.ForeignKey(PersonType, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)

I was hoping to use Django's new GeneratedFields to create a property on Book with the name author that could query the many to many relationship and set the value equal to the first Person with the "AUTHOR" PersonType. I'm certain there are other ways of doing this with Managers and what not, but I'm curious as to how I can do this with Django's new GeneratedFields, if that's even possible.

The documentation on Django's Query expressions doesn't show any examples along relationships, so I'm not sure if it's possible to do anything there.


Solution

  • As documented GeneratedField.expression

    The expressions should be deterministic and only reference fields within the model (in the same database table)

    Following is basically implementation of Generated columns (GENERATED ALWAYS AS)