Get multiple rows with one query in django?

后端 未结 2 702

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 17:55

    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

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题