GenericForeignKey tries to give you a ForeignKey
behavior but instead to be against one type of object, they do it for a set of object types (that’s why they are defined with 2 columns, 1 to keep the primary_key
and another to keep the content_type
).
GenericRelation
is the reverse relation of a GenericForeignKey
, because Django does not automatically create reverse relations for GenericForeignKeys
(unlike ForeignKeys
) you have to setup them manually.
Consider a case, where we have two model post and profile. We want to write comment for both model. Let’s see how that model looks.
Running some queries in the Django shell
How to Use
comment = Comment.objects.create(content_type=ContentType.objects.get_for_model(Post), object_id=1, text=’Great post!’) post = comment.content_object # Access the related BlogPost directly
Content Type feild: The content_type
field is a ForeignKey to the ContentType
model in Django’s contenttypes
framework. This field stores a reference to the type of the related object.
Object Type Field: The object_id
field is a PositiveIntegerField that stores the primary key (ID) of the related object.
Content Object Field: The content_object
field is not an actual database field; instead, it is a property created using Django’s GenericForeignKey
.
View
URL
UI
Summary:
- GenericForeignKey and GenericRelation allow you to create flexible relationships between models.
- They are useful when you want a model to be related to multiple other models without creating a direct ForeignKey for each relationship.
- The content_type and object_id fields together represent a polymorphic relationship, where a model can be related to any other model in the system.
- Generic relationships are particularly helpful when you are building extensible and reusable apps, such as commenting systems, tagging systems, or activity feeds.