How to get the latest entry of a Django model?
Problem
So I am trying to make a webpage that on the first page puts the three latest recipes that have been added. I know how to loop through all of the recipes, but I am having trouble finding out how to call only the latest, second-latest, and third-latest recipes. Here is my models:
class Recipe(models.Model): """A recipe the user is learning about."""
text = models.CharField(max_length=200, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self): """Return a string representation of the model.""" return self.text |
Here is my view
@login_required def recipes(request): """Show all recipes""" recipes = Recipe.objects.filter(owner=request.user).order_by("-date_added") context = {"recipes": recipes} return render(request, "recipe_book/recipes.xhtml", context)
@login_required def recipe(request, recipe_id): """Show a single recipe and all its entries""" recipe = Recipe.objects.get(id=recipe_id) # Make sure the recipe belongs to the current user if recipe.owner != request.user: raise Http404 # Show all entries for this recipe ingredients = recipe.ingredient_set.order_by("-time_added") context = { "recipe": recipe, "ingredients": ingredients, } return render(request, "recipe_book/recipe.xhtml", context) |
My URL
app_name = "recipe_book" ... # Page that shows all recipes path("recipes/", views.recipes, name="recipes"), # Detail page for a single recipe path("recipes/<int:recipe_id>/", views.recipe, name="recipe"), |
In my index, I am trying to make buttons that link to those 3 latest recipes that have been added.
I tried making a new view and url pattern but it did not work, or I didn't know how to code them.
Solution
You limit the query set through slicing:
@login_required def recipes(request): """Show all recipes""" # 🖟 slice [:3] recipes = Recipe.objects.filter(owner=request.user).order_by('-date_added')[ :3 ] context = {'recipes': recipes} return render(request, 'recipe_book/recipes.xhtml', context) |
Answered by: >Willem Van Onsem
Credit: >StackOverflow
Blog Links:
>How to manage the Text in the container in Django?
>Fix webapp stops working issue in Django- Python webapp
>Creating a form in Django to upload a picture from the website
>Sending Audio file from Django to Vue
>How to keep all query parameters intact when changing page in Django?
>Solved: TaskList View in Django
>Implement nested serializers in the Django rest framework
>How to filter events by month in Django?
>Sorting the restframework in Django
>Ways to access instances of models in view in order to save both forms at once in Django
>What makes index.html have such kind of name in Django?
>Fix Module Not Found during Deployment- Django
>Creating a Django with existing directories, files, etc.?
>How to Read a CSV file with PHP using cURL?