【问题标题】:can't get django views to filter objects by category (foreignkey attribute)无法让 django 视图按类别过滤对象(外键属性)
【发布时间】:2020-12-17 19:01:23
【问题描述】:

所以,我有这门课,并想根据类别(这是一个外键)过滤测验列表。我希望视图仅显示每个类别的测验,例如“历史”、“化学”等。

class QuizListView(generic.ListView):
    #model = Quiz
    queryset = Quiz.objects.filter(Category='History')

型号:

class Quiz(models.Model):

    title = models.CharField(
        verbose_name=_("Titulli"),
        max_length=60, blank=False)

    description = models.TextField(
        verbose_name=_("Përshkrimi"),
        blank=True, help_text=_("a description of the quiz"))

    url = models.SlugField(
        max_length=60, blank=False,
        help_text=_("a user friendly url"),
        verbose_name=_("user friendly url"))

    category = models.ForeignKey(
        Category, null=True, blank=True,
        verbose_name=_("Kategoria"), on_delete=models.CASCADE)

类别类:

class Category(models.Model):

    category = models.CharField(
        verbose_name=_("Category"),
        max_length=250, blank=True,
        unique=True, null=True)

    objects = CategoryManager()

    class Meta:
        verbose_name = _("Kategori")
        verbose_name_plural = _("Kategoritë")

    def __str__(self):
        return self.category

这是终端上的错误:

无法将关键字“quiz_category”解析为字段。选项有:answers_at_end、categor y、category_id、data_postimit、描述、草稿、exam_paper、fail_text、id、max_questions、pass_mark、问题、random_o rder、single_attempt、坐、success_text、title、url

尝试了其他方法,但似乎无法弄清楚,非常感谢任何帮助

【问题讨论】:

  • 它是category(小写),而不是Category
  • 很好,这是我尝试并得到的结果之一:ValueError: Field 'id' expected a number but got 'Histori'。
  • 是的,你需要过滤category字段,所以category__category=...
  • 也试过了,这是错误:无法将关键字“category_category”解析为字段。选项有:answers_at_end、category、category_id、data_postimit、description、draft、exam_paper、fail_text、id、max_questions、pass_mark、question、rand om_order、single_attempt、sitting、success_text、title、url
  • 不是category_category,带有两个下划线(__)。

标签: django-models django-views django-filters


【解决方案1】:

category 指的是一个Category 对象,如果要过滤相关category 对象的category 字段的值,则使用双下划线(__),所以:

class QuizListView(generic.ListView):
    model = Quiz
    queryset = Quiz.objects.filter(category__category='History')

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 2010-12-31
    • 2017-02-04
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2022-09-26
    • 1970-01-01
    相关资源
    最近更新 更多