41👍
✅
It’s seems weird because of how indexing into a queryset works.
c = list(Car.objects.filter(id__in=(1,2))) # query
print(c[0].license + c[0].vin) #no query
print(c[1].license + c[1].vin) #no query
If you do the following, you’ll only have one query too:
for car in Car.objects.filter(id__in=(1,2)):
print(car.license + car.vin)
As @Torsten said, in your situation it appears like you’re simply trying to get all the cars you’ve created. This can be achieved via the all()
method:
for car in Car.objects.all():
print(car.license + car.vin)
7👍
Great example. A typo I think though in your last codeblock. Should be:
for car in Car.objects.filter(id__in=(1,2)):
print(car.license + car.vin)
How does that method stack up
- [Django]-Custom django admin templates not working
- [Django]-Should I be adding the Django migration files in the .gitignore file?
- [Django]-Django removing object from ManyToMany relationship
Source:stackexchange.com