Python 如何筛选模型中的对象,使其外键在django中不为null?
我有这两种型号:Python 如何筛选模型中的对象,使其外键在django中不为null?,python,django,django-models,Python,Django,Django Models,我有这两种型号: class Questions(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) ch
class Questions(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
在views.py中,我只想返回最后5个有选择的问题。换言之,没有选择的问题不会返回。
我的看法是:
我应该在返回声明中应用什么更改
对不起,我的英语不好。多谢各位
return Question.objects.filter(question_set__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
这将向后使用以下外键关系,如Django文档中所述
Choice.question\u set.all()
用于通过从Choice
向后跟踪关系,获取所有具有选择权的question
对象,重新编写get\u queryset()
,如下所示
def get_queryset(self):
return Question.objects.filter(question__isnull=False,pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
您不需要相关的_名称。是的,不需要,但必须用作参考。无论如何,如果你愿意,我会编辑我的答案
Choice.question_set.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
def get_queryset(self):
return Question.objects.filter(question__isnull=False,pub_date__lte=timezone.now()).order_by('-pub_date')[:5]