Reputation: 1697
How to correctly display ManyToMany ID matching list?
My report list (weekly, monthly etc):
Car Number 1:
-customer (date, name etc)
-customer (date, name etc)
Car Number 2:
-customer (date, name etc)
-customer (date, name etc)
My Models:
class Car(models.Model):
name ...
class Reservation(model.Models):
cars = models.ManyToManyField('Car', related_name="reservation")
customerinfo = ...
As each customer can reserve multiple cars, I have to use M2M field.
Now displaying the list :
{% for car in cars %}
<h1>{{ car.name }}</h1>
{% for reservation in reservations %}
{% for reservationcar in reservation.cars.all %}
{% if reservationcar.id = car.id %}
<h2>{{ reservation.cusotmerinfo }}</h2>
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
Now, the above works, but doesnt look right and looks quite dirty.
Is there a better, cleaner, shorter way to accomplish that?
Upvotes: 1
Views: 66
Reputation: 4271
The M-M is "wrong" you can user this It will looks like something like this (not tested)
class User(models.Model):
.. any data you need ..
class Car(models.Model):
.. any data you need ..
reservations = models.ManyToManyField(User, through='Reservations')
class Reservations(models.Model):
car = models.ForeignKey(Car)
user = models.ForeignKey(User)
.. any data you need ..
You can probably place the reservations in the user and change the ref.
Upvotes: 1
Reputation: 5906
It's quicker to do a query in the views.py and add the resulting queryset to the context of the view. Or use reverse by related_name. Also with the suggested through table. All you do in templates should be minimized for performance. So do the real 'math' in python (e.g. in the views class).
in the example given also in the comments: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
Upvotes: 1