Reputation: 189
Say I have these pseudo models
class Client(models.Model
name = ...
class Property(models.Model):
client = models.ForeignKey(Client ...)
name = ...
type = ...
value = ...
For example, I have 2 clients. Each have 2 Property records. It is possible for 2 clients to own the same property, but have unique property records as each client may own a different portion of the property (value).
How can I produce a results such that it returns something like:
propertyA, {clientA, value}, {clientB, value}
propertyB, {clientA, value}
where the property is grouped on the name and type of the property?
Many thanks
iodb are you suggesting something like this?
class Client(models.Model
name = ...
class Property(models.Model):
name = ...
type = ...
class PropertyValue(models.Model):
client = models.ForeignKey(Client ...)
property = models.ForeignKey(Property ...)
value = models.IntegerField(...)
Upvotes: 1
Views: 52
Reputation: 600059
Your models don't seem appropriate for the data you want to store and the result you want to get. You need to split property and value, so that there is a many-to-many relationship between Property and Client with PropertyValue as the intermediate class.
class Client(models.Model):
name = ...
properties = models.ManyToManyField('Property', through='PropertyValue')
class PropertyValue(models.Model):
client = models.ForeignKey('Client' ...)
property = models.ForeignKey('Property'...)
value = ...
class Property(models.Model):
name = ...
type = ...
Now you can iterate over Properties and for each one output the value for each client:
{% for property in properties %}
{{ property.name }}
{% for value in property.propertyvalue_set.all %}
{{ value.client.name }}
{{ value.value }}
{% endfor %}
{% endfor %}
Upvotes: 3