0

I'm looking for right ways to override the create() method of a subclass.

Basically I'm doing this:

class Base(models.Model):
    field1_base = models.IntegerField()
    def __init__(self, field1_base):
        # LOGICS
        self.field1_base = field1_base

class A(Base):
    field2_sub = models.IntegerField()
    def __init__(self, field2_sub, field1_base):
        # LOGICS
        self.field2_sub = field2_sub
        super(A, self).__init__(field1_base)

A(field2_sub=1, field1_base=2)

However we can't override the __init__() method of a model.

I just want to leave some fields to be assigned in base class's methods.

Is there a proper way to do this using create() method?

Of course I can custom create method of Base class, however what I want is to invoke Base.create and A.create at the same time on the creation of A, which makes the situation different from this question

5
  • 1
    possible duplicate to stackoverflow.com/questions/39483184/… and stackoverflow.com/questions/843580/… Commented Sep 15, 2016 at 4:56
  • yup you can use a simple classmethod as explained in the answer Commented Sep 15, 2016 at 5:03
  • @SardorbekImomaliev Quite similar I think. However in my case I need to invoke the base model's methods at the same time. Commented Sep 15, 2016 at 5:18
  • I don't get it. Why not call super(A, self).create() then? Or you want to create Base and A objects at the same time with A.create()? Commented Sep 15, 2016 at 5:24
  • SardorbekImomaliev thank you for your answer. I want to split the logic into two parts, Base.create() and A.create(). How can I call both on the creation of instance of class A? Commented Sep 15, 2016 at 5:40

1 Answer 1

1

I would do something like this.

class Base(models.Model):
    field1_base = models.IntegerField()

    def initialize(self, *args, **kwargs):
        self.field1_base = kwargs['field1_base']

    @classmethod
    def create(cls, *args, **kwargs):
        # LOGICS
        self = cls()
        self.initialize(*args, **kwargs)
        return self

class A(Base):
    field2_sub = models.IntegerField()

    def initialize(self, *args, **kwargs):
        super(A, self).initialize(*args, **kwargs)
        self.field2_sub = kwargs['field1_base']

A.create(field2_sub=1, field1_base=2)
Sign up to request clarification or add additional context in comments.

1 Comment

It is a right answer, and actually I'm using the same work around. However I'm still looking for an elegant way of doing so. Thank you all the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.