2

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.

Ben S
  • 1,407
  • 1
  • 13
  • 27
  • Read your own code again. Why would company have an address_set? – Marcin Feb 16 '12 at 16:46
  • 1
    I guess that's my question. If I were to specify a foreign key relationship in `Address` that pointed to `Company`, then `Company` would have an address_set. So, I would like to know how I can accomplish the same thing with a generic relationship, since `Address` can be associated with `Company` or a host of other models. – Ben S Feb 16 '12 at 16:49

1 Answers1

7

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Jingo
  • 3,200
  • 22
  • 29