Django ORM:覆盖子类中字段的related_name [英] Django ORM: Override related_name of Field in Child Class

查看:162
本文介绍了Django ORM:覆盖子类中字段的related_name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这个异常:


django.core.exceptions.FieldError:

django.core.exceptions.FieldError:

'SpecialPlugin'类中的本地字段'ticket'与基类'BasePlugin'中的相似名称字段发生冲突

Local field 'ticket' in class 'SpecialPlugin' clashes with field of similar name from base class 'BasePlugin'

我的模型:

class BasePlugin(models.Model):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True, 
                                  related_name='%(app_label)s_%(class)s')

    class Meta(IndexImplementation.Meta):
        abstract = True

    # .. Other stuff which should be available for SpecialPlugin 
    #    and other child classes.

class SpecialPlugin(BasePlugin):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True, 
                                  related_name='special')

我仅找到了此注释,但在我的情况下,父类是抽象的。我不确定在这里是否适用。

I only found this note, but in my case the parent class is abstract. I am unsure if it applies here.

我想给子类 SpecialPlugin 相关名称 special因为BasePlugin的相关名称(%(app_label)s _%(class)s )会破坏旧代码。

I want to give the child class SpecialPlugin the related name "special" since the related name (%(app_label)s_%(class)s) of the BasePlugin would break old code.

是否可以给SpecialPlugin.ticket关联名特殊?

Is there a way to give SpecialPlugin.ticket the related_name "special"?

推荐答案

更新:

可以使用django的 default_related_name 元选项。

Similar thing can be done using django's default_related_name meta option.

这看起来很丑陋,但是您可以将函数调用设置为 related_name 参数而不是字符串。然后在子类/模型中重写该函数。

It might look like an ugly hack, but you can set a function call to the related_name argument instead of string. And then override that function in the child class/model.

class BasePlugin(models.Model):

    @staticmethod
    def get_ticket_related_name():
        return '%(app_label)s_%(class)s'

    ticket = models.OneToOneField('foobar.ticket', primary_key=True, 
                                  related_name=get_ticket_related_name.__func__())

    class Meta(IndexImplementation.Meta):
        abstract = True


class SpecialPlugin(BasePlugin):
    @staticmethod
    def get_ticket_related_name():
        return 'special'

这篇关于Django ORM:覆盖子类中字段的related_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆