Django - Getting last object created, simultaneous filters

后端 未结 7 2110
花落未央
花落未央 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: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.

提交回复
热议问题