对于每个问题,都有很多答案。我有一个表投票,其中包含所有问题和答案的upvote / downvotes。我想执行类似的查询:
从投票中选择* WHERE username =" some username" AND(QID ="问题" 或(AID IN(来自Answers的选择AID,QERE ="问题")))
class Question(models.Model):
QID = models.CharField( default="",max_length=5, primary_key=True)
title = models.CharField(max_length=30, default="")
description = models.CharField(max_length=1055, default="")
date = models.DateTimeField(default=datetime.now, blank=True)
username = models.CharField(max_length=30, default="")
votes = models.IntegerField(default=0)
approved = models.BooleanField(default=False)
def __str__(self):
return self.title
class Answer(models.Model):
AID = models.CharField(max_length=5, default="", primary_key=True)
QID = models.ForeignKey(Question,on_delete=None)
description = models.CharField(max_length=1055, default="")
date = models.DateTimeField(default=datetime.now, blank=True)
username = models.CharField(max_length=30, default="")
votes = models.IntegerField(default=0)
approved = models.BooleanField(default=False)
def __str__(self):
return self.AID
class Vote(models.Model):
username = models.ForeignKey(User,on_delete=None)
QID = models.ForeignKey(Question,on_delete=None, null=True, blank=True)
AID = models.ForeignKey(Answer,on_delete=None, null=True, blank=True)
vote = models.BooleanField(default=True)
def __str__(self):
if self.QID is not None:
return self.QID.QID+'_'+self.username.username+'_'+str(self.vote)
else:
return self.AID.AID+'_'+self.username.username+'_'+str(self.vote)
P.S。请注意,QID和AID是外键。所以他们只会采用问题/答案模型的实例。
答案 0 :(得分:1)
你可以,
from django.db.models import Q
Vote.objects.filter(username='some_username').filter(
Q(QID=question_id) |
Q(AID__QID=question_id
)
注意:完全同意@ schillingt的回答。
或者,如果您想获得问题的所有Vote
个对象,那么您可以调用反向关系,例如,
question = Question.objects.get(QID='some_id')
question.vote_set.all()
答案 1 :(得分:0)
我认为更好的方法是:
from django.db.models import Q
Vote.objects.filter(username='some_username').filter(
Q(QID=question_id) |
Q(AID___QID=question_id)
)
它避免了Fazil Zaid的答案中的额外查询,即通过在单个查询中执行此操作来获取给定问题ID的答案ID。