繁体   English   中英

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

[英]Django: Filtering query with foreign key not working

我想用外键过滤查询,但是它似乎不想识别它。 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)

您的status本身就是一个模型,因此您应该这样做:

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

另外,我认为您的设计没有太大意义。 如果只需要一个字符串作为状态作为Incident ,则不需要模型Status ,只需将status字段设为Incident ,您的旧查询就可以使用。

编辑:如果要将选择限制为特定集合,则应考虑使用choiceshttps : //docs.djangoproject.com/zh-CN/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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM