I am building a Blog application in Django and currently stuck at Querying the Data. I am creating a Post and then uploading multiple images to that post.
This is my Blog Post Model.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
title = models.CharField(max_length=255)
description = models.CharField(max_length=1000,null=True)
Tags = models.CharField(max_length = 255,null=True,blank=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
And this is my Images Model
class Images(models.Model):
Post = models.ForeignKey(Post,on_delete=models.CASCADE)
image = models.ImageField(upload_to='media/')
Now using this implementation I have 2 tables in DB in which data is stored as expected. In the first tables all the details related to Post are being stored and in the second Table ID, Post_Id, Image_URL is being stored. If I upload 3 images then three rows are being created.
Now I want to Query the data that is -> I want all the posts and I want all the Images according to the Posts.
I can get seprate queries for Post and Images but how can this be done in Django ORM? How can I query The data?
CodePudding user response:
You can use like this;
post = Post.objects.all().prefetch_related('images_set').get(pk=1)
images = post.images_set.all() # this will bring you all images related to
post
CodePudding user response:
Assuming you have a view that populates a context variable named posts
with a queryset like Post.objects.all()
your template could look something like this simplified
{% for post in posts %}
{{ post.title }}
{{ post.category }}
{{ post.description }}
...
{% for image in post.images_set.all %}
{{ image.image.url }}
{% endfor %}
{% endfor %}
Every time you iterate over post.images_set.all
you will execute another query, you should use prefetch_related
so that you don't perform a query each time and the data is cached
posts = Post.objects.prefetch_related('images_set')