【问题标题】:django_filters picking up %(app_label)s_related_name as field namedjango_filters 选择 %(app_label)s_related_name 作为字段名
【发布时间】:2016-11-04 22:21:29
【问题描述】:

(Django 1.8.14) 所以我有一个模型,它使用 ContentType 指向跨不同应用程序的模型集合。

我希望能够“插入”将该模型链接到单独应用程序中的其他模型的功能。所以我们有以下内容:

class MyModelMixin(models.Model):
    """ Mixin to get the TheModel data into a MyModel
    """
    updated_date = models.DateTimeField(null=True, blank=True)
    submission = GenericRelation(
        TheModel,
        related_query_name='%(app_label)s_the_related_name')
    class Meta:
        abstract = True

主模型模型如下所示:

class TheModel(models.Model):
    """ This tracks a specific submission.
    """
    updated = models.DateTimeField()
    status = models.CharField(max_length=32, blank=True, null=True)
    final_score = models.DecimalField(
        decimal_places=2, max_digits=30, default=-1,
    )
    config = models.ForeignKey(Config, blank=True, null=True)
    content_type = models.ForeignKey(
        ContentType,
        blank=True,
        null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    my_model_instance = GenericForeignKey()

mixin 包含在 MyModel 模型中,可用于许多不同的应用程序。

为此使用过滤器时,使用 django 过滤器时,会出现问题。我有一个过滤器,它应该在使用时实例化到每个应用程序。但是,当我实例化时,例如,使用

class MyFilterSet(Filterset):
    def __init__(self, *args, **kwargs):
        self.config_pk = kwargs.pop('config_pk', None)
        if not self.config_pk:
            return
        self.config = models.Config.objects.get(pk=self.config_pk)
        self.custom_ordering["c_name"] =\
            "field_one__{}_the_related_name__name".format(
                     self.config.app_model.app_label,
                )
        super(MyFilterSet,self).__init__(*args, **kwargs)

但是,当我使用它时,我得到了

FieldError: Cannot resolve keyword 'my_app_the_related_name field. Choices are: %(app_label)s_the_related_name, answers, config, config_id, content_type, content_type_id, final_score, form, form_id, id, object_id, section_scores, status, updated

%(app_label)s_the_related_name 如何在字段集中,我怎样才能使其正确呈现(就像它在 django 过滤器之外一样)或有其他解决方案。

【问题讨论】:

    标签: django django-filter django-filters


    【解决方案1】:

    您可能遇到过issue #25354。在 GenericRelation 上模板化 related_query_name 在 Django 1.9 或更低版本上无法正常工作。

    fix 合并后,在 Django 1.10 中添加了 related_query_name now supports app label and class interpolation using the '%(app_label)s' and '%(class)s' strings

    【讨论】:

    • 哦,很高兴知道。因为我已经深入研究了来源。
    • 我在源码中已经很久了——非常感谢。
    猜你喜欢
    • 2022-01-09
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2016-10-23
    • 2014-07-26
    • 2011-06-21
    相关资源
    最近更新 更多