1024programmer Java DjangoORM: Overriding related_name of Field in subclass

DjangoORM: Overriding related_name of Field in subclass

I get this exception:

django.core.exceptions.FieldError:

The local field “ticket” in the “SpecialPlugin” class conflicts with a similarly named field in the base class “BasePlugin”

This is my model:

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 comment, but in my case the parent class is abstract. I’m not sure if it applies here.

I want to provide the SpecialPlugin related name “special” to the subclass, because the related name() of %(app_label)s_%(class)sBasePlugin will break Old code.

Is there a way to give SpecialPlugin.ticket the relevant “special”?

1> v1k45..:


It may look like an ugly hack, but you can set a function to call default_related_name Parameter instead of string. Then override the function in subclass/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'
 


get_ticket_related_name in my subclass is never called.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/763150

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索