R
R
Rostislav Biloshapka2019-01-22 16:07:41
Django
Rostislav Biloshapka, 2019-01-22 16:07:41

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'

Unfortunately, this method does not work, what needs to be done to make it work? I didn’t find an answer anywhere, because I don’t know how to formulate the question correctly, but I don’t want to override it in children, because there can be many of them and some are extended by other classes.
This also doesn't work:
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

2 answer(s)
A
Astrohas, 2019-01-22
@Rostislav_B

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')

Y
Yura Khlyan, 2019-01-22
@MAGistr_MTM

In my opinion, something similar is implemented in Django-Oscar.
There, the model is OfferconnectedBenefit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question