Django Get Latest Entry from Database

前端 未结 5 1419
星月不相逢
星月不相逢 2020-12-11 02:46

I\'ve got 2 questions, but they are related to the same topic.

I know how to retrieve data from a for loop using template tags

{% for st         


        
5条回答
  •  甜味超标
    2020-12-11 03:39

    Let us assume I have a Model named "OneOfTheModelsUsed" and there is a field called "car_name" and "date" within this model.

    The following code worked for me while I was using Django FormWizard. After going through all the steps in the form and it gets saved. I used

    last_entry = OneOfTheModelsUsed.objects.latest("date")
    

    This gives all the entries in that model

    last_car_name = last_entry.car_name
    

    This gives the specific field entry you want in the given form.

    return render(request, 'reference.html', {'last_car_name':last_car_name,}
    

    passed the data to a template.

    for the display in the template I used

    {{last_car_model}}
    

    and if you need the id for that entry.. use this {{last_car_model.id}} in the template.

    PS:I'm fairly new to Django and Web development as a whole so I don't know much of the technical terms for all this

提交回复
热议问题