I'm trying to model something in Django and it doesn't seem quite right. A Book
and a Movie
can have one or more Person
s involved in it, each of whom has a Role
(like "Author" or "Director") on that Book
or Movie
.
I'm doing this with Generic relations something like this:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=255)
class Role(models.Model):
person = models.ForeignKey('Person')
role_name = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Book(models.Model):
title = models.CharField(max_length=255)
roles = GenericRelation('Role', related_query_name='books')
class Movie(models.Model):
title = models.CharField(max_length=255)
roles = GenericRelation('Role', related_query_name='movies')
Which seems to work, but it seems odd when getting all the Book
s a Person
has worked on:
person = Person.objects.get(pk=1)
for role in person.role_set.all():
print(role.role_name)
for book in role.books.all():
print(book.title)
The for book in role.books.all()
feels wrong - like a role can have multiple books. I think I want a more direct relationship between a person working on a particular book/movie.
Is there a better way to model this?