Search code examples
pythondjangomanytomanyfield

Django, ManyToMany field, get the right object with extra fields


I have 2 models: User and a Car, and I want to create a field for user, which keeps a list of user's cars. I have created 3 classes:

class Car():
   type = ...

class User():
   name = ...
   cars = models.ManyToManyField(Car, through='CarList')

class CarList():
   owner = models.ForeignKey(User)
   car_type = models.ForeignKey(Car)
   extra_field = ...
   extra_field2 = ...

Now when I want to get the user's cars, I can use the User.cars.all() "function", which returns the list of all of his cars. Which is all fair and good except it returns a list of foreign keys of Car objects instead of CarList objects (which have extra fields !!)

I know I can use a different query, like: CarList.objects.get(owner=user, car_type=user.cars.all()[0]), etc... but this is just inconvenient.

So is there a query which will give me the "CarList" objects ?


Solution

  • If I understand you correctly, you have a User, and you want to get the CarList. Since you have a ForeignKey from CarList to User, that is a simple backwards relation:

    carlists = user.carlist_set.all()