Django:使用外键过滤查询不起作用

3

我想使用外键过滤查询,但似乎它不愿认可。 status 可以是 'open' 或者 'closed'

models.py

class Status(models.Model):
    status = models.CharField(primary_key=True, max_length=100)

class Incident(models.Model):
    incident_date_reported = models.DateField('Date Reported', default=timezone.now)
    status = models.ForeignKey(Status, default="open")

views.py

def index(request):

    template = "index.html"                 
    form = IncidentSearchForm(request.GET)

    if request.method == 'GET':

        form = IncidentSearchForm()

        ############## MY QUERY THAT DOESN'T LIKE THE FOREIGN KEY #############
        incident_list = Incident.objects.filter(status = 'open').order_by('-incident_date_reported')
        #######################################################################

       context = {  "form": form,
                    "incident_list": incident_list
                  }

        return render(request, template, context)
1个回答

4

你的status是一个独立的模型,因此你应该这样做:

incident_list = Incident.objects.filter(status__status='open').order_by('-incident_date_reported')

此外,我认为你的设计没有太多意义。如果你只需要一个字符串作为Incident的状态,那么你不需要模型Status,只需将status字段添加到Incident中,你以前的查询仍然有效。 编辑: 如果你想限制选择为特定的一组,你应该考虑使用choiceshttps://docs.djangoproject.com/en/1.8/ref/models/fields/#choices 那么你的模型就变成了:
class Incident(models.Model):
    STATUS_CHOICES = (
        ('open',   'Open'),
        ('closed', 'Closed'),
        # some other statuses go here
    )
    incident_date_reported = models.DateField('Date Reported',
                                              default=timezone.now)
    status = models.CharField(max_length=20,
                              choices=STATUS_CHOICES,
                              default='open')

我仍然无法让它正常工作。此外,我希望使数据更加严格,以便用户只能从有限的选项中选择(在这种情况下为2,希望将来有更多),这就是我将状态设置为模型的原因。__应该可以工作...我不知道。 - user1807271
1
它为什么不工作?你看到了什么?你收到了哪些错误? - Daniel Roseman
我更新了你的答案。请阅读Django文档以获取更多信息。 - Shang Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接