Menggunakan Annotate di Django

Misal ada 2 model, dengan model relasi One-to-Many, Post dan Image. Satu Post punya banyak Image. Bagaimana kita dapat menghitung jumlah image di masing-masing post? Menggunakan annotate kita dapat melakukan query ini dengan satu langkah mudah.

Berikut ini gambaran models.py

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=255)


class Image(models.Model):
    post_image = models.ForeignKey(Post)
    image = models.ImageField(upload_to='assets/')

Contoh query:

>>> from django.db.models import Count
>>> Post.objects.annotate(Count('image'))

Filter semua Post yang memiliki image saja

>>> Post.objects.annotate(num_images=Count('image')).filter(num_images__gt=0)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s