【问题标题】:How would I properly write this query in django?我将如何在 django 中正确编写此查询?
【发布时间】:2014-07-05 10:29:54
【问题描述】:

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,但我不太明白,谢谢

【问题讨论】:

  • 老实说,我很困惑。你能粘贴整个模型,而不仅仅是字段吗?
  • 对不起,我以为我做到了,我能够使用 Q 方法获得一个组合列表,但是我无法提取出我需要的确切字段。 dancer_1_fname 或 team_name。
  • 为什么必须是一个列表?你不能只有一个注册的团队列表和一个单独的个人列表吗?顺便说一句,给类/模型命名是名词并且总是以大写开头。
  • 拥有两个不同的列表是我所做的,但是当需要向贝宝提交购物车时,我使用 forloop 计数器来跟踪每个提交。由于它们不在同一个查询集中,我得到两个不同的 for 循环,两个重复的数字

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


【解决方案1】:

使用来自 itertools 的链,

首先

from itertools import chain in the top of your views

然后创建要组合的查询

最后,调用

somename = list(chain(query1, query2))

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

【讨论】:

    【解决方案2】:

    使用后向关系:

    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() 
    

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多