Tôi có một chức năng mà trông như thế này:Lọc Uẩn trong Django ORM
def post_count(self):
return self.thread_set.aggregate(num_posts=Count('post'))['num_posts']
Tôi chỉ muốn đếm bài viết mà có tư cách của họ được đánh dấu là 'hoạt động'. Có cách nào dễ dàng để thêm bộ lọc trước hàm Count không?
Mẫu Định nghĩa:
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, blank=True, primary_key=True)
ordering = models.IntegerField(max_length=3, default=0)
@property
def thread_count(self):
return self.thread_set.all().count()
@property
def post_count(self):
return self.thread_set.aggregate(num_posts=Count('post'))['num_posts']
class Thread(models.Model):
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
latest_activity = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
thread = models.ForeignKey(Thread)
parent = models.ForeignKey('Post', null=True, blank=True)
display_name = models.CharField(max_length=100)
email = models.EmailField(db_index=True)
ip_address = models.IPAddressField(null=True, blank=True)
content = models.TextField()
status = models.CharField(choices=STATUS_CHOICES, max_length=25, db_index=True, default='approved')
created = models.DateTimeField()
Mô hình của bạn trông như thế nào? – Mayuresh