Django - Getting last object created, simultaneous filters

后端 未结 7 2086
花落未央
花落未央 2020-12-24 00:39

Apologies, I am completely new to Django and Python.

I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of obj

相关标签:
7条回答
  • 2020-12-24 01:17

    this works!

    Model.objects.latest('field') - field can be id. that will be the latest id

    0 讨论(0)
  • 2020-12-24 01:19

    I am working on Django version is 1.4.22, neither last nor lastet is working. My way to solve with minimum db loading is like:

    latest = lambda model_objects, field : model_objects.values_list( field, flat = True ).order_by( "-" + field )[ 0 ]
    latest_pk = latest( List.objects, "pk" )
    

    This function accepts query_set as input.

    You may bind this function dynamically by doing:

    import types
    List.objects.latest = types.MethodType( latest, List.objects )
    

    Then you should be able to get the last object by this latest pk easily.

    0 讨论(0)
  • 2020-12-24 01:21

    alternative for the latest object created:

    List.objects.all()[List.objects.count()-1]
    

    It is necessary to add an AssertionError for the case when there are no items in the list.

    except AssertionError:
       ...
    
    0 讨论(0)
  • 2020-12-24 01:23

    For the largest primary key, try this:

    List.objects.order_by('-pk')[0]
    

    Note that using pk works regardless of the actual name of the field defined as your primary key.

    0 讨论(0)
  • 2020-12-24 01:25

    You can use the count() method on a query set the get the number of items.

    list = List.objects.all()
    list.count()
    

    Arguments to filter are "AND"ed together. If you need to do OR filters look at Q objects. http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

    0 讨论(0)
  • 2020-12-24 01:28

    Since Django 1.6 - last

    last()

    Works like first(), but returns the last object in the queryset.

    Returns the last object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

    list = List.objects.last() gives you the last object created

    0 讨论(0)
提交回复
热议问题