Tell me how to make a request through Model.objects.get () or through Model.objects.filter () to get the last created model. There is a field

create_date = models.DateField( 'Создан', auto_now_add=True ) 

    4 answers 4

    In the model in the meta you can define the field get_latest_by :

     get_latest_by = "create_date" 

    Then request

     Model.objects.latest() 

    will give you the latest model sorted by the create_date field, and the query

     Model.objects.earliest() 

    will issue the first created model.

    • thanks, this is what you need. - Vetos

    Last created object

     Model.objects.latest('create_date') 
    • I think in this case, the request will return a bunch of objects, and this may take up memory. - Vetos
    • Checked, returned one last entry. Without a zero index, everything will be sorted by date in the reverse order. - Dmitry Erohin
    • The question is how many objects are returned from the base. There is a suspicion that a lot, and then by the forces of Django, get out alone. - Vetos
    • one is chosen not by the forces of jangi, but django returns everything. - Dmitry Erohin
    • changed your comment, read. - Dmitry Erohin
     model = Model.objects.all().order_by("create_date").last() 

    PS: did not check. It translates to how to select all the models, sort them by date of creation and take the latest model from there.

    • and you found this method in docks? - Vetos

    Use a slice, django understands it correctly

     Model.objects.all().order_by('-create_date')[:1]