Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Query Multiple Tables in Django and geta consolidated result

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading