Get multiple rows with one query in django?

后端 未结 2 727

How can I get build a QuerySet that gets multiple rows from django? I thought filter() would work, but it seems to be worse off.

For example, I have two rows in the mode

2条回答
  •  生来不讨喜
    2021-02-01 18:04

    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)
    

提交回复
热议问题