Search code examples
djangodjango-modelsgeneric-relations

generic relation model declaration


Just a quick noob question. Do I need to have content_type, object_id, and content_object every time I use GenericRelation in models? I get the concept behind generic relation but I'm confused on how to implement it.

Below is the setup.

Address - a generic content type; to be used in different models.

Company - a simple model that uses address generic content type.

Person - a simple model that uses address generic content type.

Is it essential to have these 3 attributes in all models? Thanks in advance!


Solution

  • You need this fields only inside Address model:

    class Address(models.Model):
        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type', 'object_id')
    

    In models Company and Person you just specify reverse generic relation with GenericRelation:

    from django.contrib.contenttypes.fields import GenericRelation
    class Company(models.Model):
        addresses = GenericRelation(Address)
    
    class Person(models.Model):
        addresses = GenericRelation(Address)
    

    with this you can get address assosiated with person like this:

     person.addresses.all()