Answer the question
In order to leave comments, you need to log in
How to dynamically change ForeignKey in children of base abstract model?
There are many similar models in which the ForeignKey is changed, is it possible to make it so that it is not overridden in children?
For example:
class AbstractTest(models.Model):
@staticmethod
def get_test_id():
return 1
test = models.ForeignKey(
get_some_model(get_test_id()), # здесь передать статический метод или что-то другое, что будет меняться в детях
null=True,
verbose_name='test',
on_delete=models.CASCADE
)
class Meta:
abstract = True
class Test1Model(AbstractTest):
@staticmethod
def get_test_id():
return 5
class Meta:
verbose_name = 'Test1Model'
verbose_name_plural = 'Test1Models'
class AbstractTest(models.Model):
F_MODEL = 'app.Default'
test = models.ForeignKey(
F_MODEL,
null=True,
verbose_name='test',
on_delete=models.CASCADE
)
class Meta:
abstract = True
class Test1Model(AbstractTest):
F_MODEL = 'app.Model'
Answer the question
In order to leave comments, you need to log in
in short, there are two ways to go -
1) Difficult - through a metaclass, decorator or something like that, but why?
2) Simple - something like that. There are no other ways.
def UniversalForeignKey(to, **kwargs):
return models.ForeignKey(
to=to,
null=True,
verbose_name='test',
on_delete=models.CASCADE,
**kwargs
)
class Test1(models.Model):
test = UniversalForeignKey('app_model')
In my opinion, something similar is implemented in Django-Oscar.
There, the model is Offer
connectedBenefit
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question