Django check for any exists for a query

前端 未结 3 1008
梦如初夏
梦如初夏 2021-02-01 00:12

In django how to check whether any entry exists for a query

sc=scorm.objects.filter(Header__id=qp.id)

This was how it was done in php

相关标签:
3条回答
  • 2021-02-01 00:31

    this worked for me!

    if some_queryset.objects.all().exists(): print("this table is not empty")

    0 讨论(0)
  • 2021-02-01 00:45

    Use count():

    sc=scorm.objects.filter(Header__id=qp.id)
    
    if sc.count() > 0:
       ...
    

    The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

    count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

    Having this in mind, When QuerySets are evaluated can be worth reading.


    If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

    from django.core.exceptions import ObjectDoesNotExist
    try:
        sc = scorm.objects.get(pk=someid)
    except ObjectDoesNotExist:
        print ...
    

    Update: it's also possible to use exists():

    if scorm.objects.filter(Header__id=qp.id).exists():
        ....
    

    Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

    0 讨论(0)
  • 2021-02-01 00:47

    As of Django 1.2, you can use exists():

    https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

    if some_queryset.filter(pk=entity_id).exists():
        print("Entry contained in queryset")
    
    0 讨论(0)
提交回复
热议问题