开发者

What does pk__in mean in Django?

开发者 https://www.devze.com 2022-12-18 21:53 出处:网络
Model.objects.filter(pk__in=[list of ids]) and Model.objects.filter(pk__in=[1,2,3]) How do I show this data in a tem开发者_Go百科plate?
Model.objects.filter(pk__in=[list of ids])

and

Model.objects.filter(pk__in=[1,2,3])

How do I show this data in a tem开发者_Go百科plate?

def xx(request):
    return HttpResponse(Model.objects.filter(pk__in=[1,2,3]))


It means, give me all objects of model Model that either have 1,2 or 3 as their primary key.

See Field lookups - in.

You get a list of objects back you can show them in the template like every other list, using the for template tag:

{% for object in objects %}
    Some value: {{ object.value }}
{% endfor %}

To learn how to create a Django application you should read the tutorial or the Django book.


A tricky way to batch select (a best practice when dealing with a lot of data). it would be faster than calling get/get_or_create in a loop due to the fact that only one SQL query is sent.

Try to time this :

Model.objects.filter(pk__in=[list of ids])

and this :

[Model.objects.get(pk=i) for i in ids]

Also note that running on your laptop there is minimal latency when django communicates with the database (production might be different).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号