我如何在django中正确编写此查询?

时间:2014-07-05 10:29:55

标签: django django-models django-views django-queryset

team_signupsignedup都有来自comp_name的外键。我试图将它们全部列在一个列表中,这样我就可以获得注册的个人列表以及团队。我想也许某种加入?

查看:

session = request.session._session_key    
cart = comp_name.objects.filter(Q team_signup__sessionid = session | Q signedup__sessionid = session)

模板:

{{cart}}

模型:

#for individual sign ups

class signedup(models.Model):
    comp_name = models.ForeignKey(comp_name)
    sessionid = models.CharField(max_length = 60, blank=True)
    price = models.FloatField(max_length = 7, blank=True)


    #dancer information
    dancer_1_fname = models.CharField(max_length = 30)
    dancer_1_lname = models.CharField(max_length = 30)
    dancer_1_email = models.CharField(max_length = 30)

#for team sign ups
class team_signup(models.Model):
    comp_name = models.ForeignKey(comp_name)
    sessionid = models.CharField(max_length = 60, blank=True)
    price = models.FloatField(max_length = 7, blank=True)

    #dancer information
    team_name = models.CharField(max_length = 30)
    team_count = models.CharField(max_length = 30)
    team_email = models.CharField(max_length = 30)

我可能没有使用Q权利,但我不太明白,谢谢

2 个答案:

答案 0 :(得分:0)

使用来自itertools的链

首先

from itertools import chain in the top of your views

然后创建要组合的查询

最后,请致电

somename = list(chain(query1, query2))

然后在你的模板中,就像对待任何其他查询集一样对待它

答案 1 :(得分:0)

使用落后关系:

https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

然后您可以调用您的相关字段,如

comp = comp_name.objects.get(id=1)
comp.signedup_set.all() 
comp.team_signup_set.all()