Reputation: 6555
I have the following models:
class Dog(AbstractAnimals):
pass
class Meta:
app_label = 'animals'
class Cat(AbstractAnimals):
pass
class Meta:
app_label = 'animals'
Which are abstract of:
class AbstractAnimals(models.Model):
description = models.CharField()
This is where my question comes in. If I have a House model, it can have one or both of these animals. I can think of two ways do to this, but I'm unsure which is better.
class House(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='animal', null=True)
1) Use 2 GenericForeignKey's on the House Model
2) Use 2 standard ForeignKey's.
3) another option?
Which is the better option, and or opinions? Thanks.
Upvotes: 0
Views: 135
Reputation: 3174
If House can have two animals and animal can be in only one house and you want your code to be prepared to easily add other animal types, then AbstractAnimal should have regular foreign key to House and House shouldn't have any foreign keys in this case.
This kind of relation between objects (or models or tables) is usually called "many to one": many animals are linked (or can be) to a single house.
Example usage of GenericForeignKeys is comment or tag model, where many unrelated content types can be commented or tagged (articles, blog entries, images, videos, etc.). In such case comment or tag model should have GenericForeignKey to "unknown" model. Some comments and tagging packages available on the Internet are using this pattern.
GenericForeignKey's in my opinion are best suitable when you want to write a reusable application or package in which models needs to be related to some unknown content types (other models) at the time of writing.
Upvotes: 2