morgancodes
morgancodes

Reputation: 25265

django -- how to construct and initialize a complex model object with many depenencies

I have a django model that looks something like this:

class ChildClass(Model):
    # define fields

class ParentClass(Model):
    child1 = models.ForeignKey(ChildClass)
    child2 = models.ForeignKey(ChildClass)
    child3 = models.ForeignKey(ChildClass)

Every time I create an instance of ParentClass, I need to make sure that I have valid ChildClass objects for it. Is there a proper, or standard way to create these "dependency" objects? My current plan is to create the child objects in __init__, and save them in save, like this:

class ChildClass(Model):
    # define fields

class ParentClass(Model):
    child1 = models.ForeignKey(ChildClass)
    child2 = models.ForeignKey(ChildClass)
    child3 = models.ForeignKey(ChildClass)

    def __init__(self):
        child1 = ChildClass()
        child2 = ChildClass()
        child3 = ChildClass()

    def save(self, *args, **kwargs):
        # save each child obejct if it hasn't been saved yet
        for child in [child1, child2, child3]:
            if child.pk is None:
                child.save()

        super(ParentClass, self).save(*args, **kwargs)

Is there a better way?

Upvotes: 0

Views: 212

Answers (1)

aeros
aeros

Reputation: 314

You may want to look at django signals https://docs.djangoproject.com/en/1.8/topics/signals/. Put a signal on the post_init signal for this model and have it create and associate the child models.

Here's a list of signals https://docs.djangoproject.com/en/1.8/ref/signals/

So for example:

@reciever(post_init, sender=ParentClass)
def on_parent_class_create(sender, **kwargs):
    instance = kwargs['instance']
    instance.child1 = ChildClass()
    etc...
    ...

Upvotes: 1

Related Questions