2015-05-06 73 views
0

我想显示每个通知类型和最近的一个通知。 我的问题是如何获取每种通知类型并显示最新的通知类型。Django-Filter按类型查询

notifications = Notification.objects.filter(**condition). \ 
    exclude(notification_user__in=users). \ 
    order_by('notificationType__priority','-start_date')[:1] 

models.py

class Notification(models.Model): 
title = models.CharField(max_length=75) 
description = models.TextField() 
start_date = models.DateTimeField() 
end_date = models.DateTimeField() 
application = models.ManyToManyField('Products.Application') 
notificationType = models.ForeignKey(NotificationType) 
url = models.URLField(null=True, blank=True) 
region = models.ManyToManyField('Geolocations.Region', null=True, blank=True) 
image = models.ImageField(null=True, blank=True) 
user = models.ManyToManyField(User, through='Notification_User') 

class NotificationType(models.Model): 
type = models.CharField(max_length=30) 
priority = models.IntegerField(max_length=3) 
color = RGBColorField() 

这只能说明最近的通知独立于通知类型的。 有什么建议吗?

UPDATE

现在我插入通知到列表中。 但在这种方式行不通 我的想法是,如果NOTIFICATION_TYPE的优先级值(唯一INT)不存在,要添加到列表中

notifications=[]  
if n.objects.filter(notification_type__priority=notifications).exists(): 
    notifications.append(n) 

回答

0

你可以单独捕获所有的通知,然后将它们合并到一个QuerySet

c1 = Notification.objects.filter(condition=[CONDITION1_HERE]). \ 
    exclude(notification_user__in=users). \ 
    order_by('notificationType__priority','-start_date')[:1] 

c2 = Notification.objects.filter(condition=[CONDITION2_HERE]). \ 
    exclude(notification_user__in=users). \ 
    order_by('notificationType__priority','-start_date')[:1] 

notifications = c1 | c2 # A QuerySet that merges c1 and c2 

这可以通过使用一个for循环,这样就可以使用**condition,而不必定义[CONDITION1_HERE][CONDITION2_HERE]做出更聪明,但我需要看到什么型号的样子。

+0

不错,但有一个问题。通知类型是动态的,这意味着用户可以添加他自己的通知类型,如果我有2个以上的方式不工作 –

+0

这就是我的想法 - 任何方式你可以看看模型?这将帮助我提供一个动态的解决方案。 – Hybrid

+0

增加了模型,要求 –

0

从NotificationType和extra中查询最新的相关通知。你可以参考上面的django文档或this question以获得更多灵感。