How to compare lists and get total matching items

2019-07-26 03:24发布

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)

2条回答
神经病院院长
2楼-- · 2019-07-26 04:16

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) )
查看更多
Emotional °昔
3楼-- · 2019-07-26 04:25

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.

查看更多
登录 后发表回答