Search code examples
djangodjango-templatesgeneric-relationship

How do I traverse a generic relationship in a Django template?


I would like to traverse generic relationships in my Django template, similar to how you can traverse FK relationships.

Models.py

class Company(models.Model):
    name = models.CharField(blank=True, max_length=100)
    notes = models.TextField(blank=True)

class Address(models.Model):
    address = models.TextField(max_length=200)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

This does not seem to work in my template:

{{ company.address_set.all }}

Any help is appreciated.


Solution

  • Your Company model doesnt know about the adresses, you could try this:

    class Company(models.Model):
        name = models.CharField(blank=True, max_length=100)
        notes = models.TextField(blank=True)
        addresses = generic.GenericRelation('Address', blank = True)
    

    In your template you can do something like this :

    {% for address in company.addresses.all %}
    {{ address.town }}, {{ address.street }}
    {% endfor %}
    

    Hope this helps.