问题
Garage.cars: object garage has a FK of cars
Person.carwishlst: object Person has FK of cars they would like.
In Django how to I achieve the following, loop?...
Get the total number of cars x the Person has which match the ones the Garage has.
Outcome: i.e. Grange has 4 cars you want
Hypothetical, but lets say Grange model has an FK cars = models.ManyToManyField(Cars)
Person also has a FK cars_wishlist = models.ManyToManyField(Cars)
回答1:
Assuming the cars
and carwishlst
are lists:
You would do the following
def cars_you_want(cars, carwishlst):
car_set = [val for val in cars if val in carwishlst]
return len(car_set)
That should do it.
回答2:
Supposing that Garage.cars
and Person.carwishlist
are both lists and that the contained cars have a sensible __eq__
method:
numberOfWishedCarsInGarage = len (set (garageX.cars) & set (personX.carwishlist) )
来源:https://stackoverflow.com/questions/14912949/how-to-compare-lists-and-get-total-matching-items-count