tomcounsell
tomcounsell

Reputation: 5081

Django model class creates its own dependencies

I have a model that when instantiated, needs to create new instances for its own foreign relationships. Here's an example:

class CustomOrder(models.Model):
    product = models.OneToOneField(Product)
    customer = models.ForeignKey(Customer)

When a new CustomOrder is created, CustomOrder.objects.create() it needs to create new product and customer instances to fulfill it's foreign key requirements.

Perhaps something like a class method is needed here?

@classmethod
def create(cls, base_product):
    product = Product.objects.create()
    customer = Customer.objects.create()
    return cls(product=product, customer=customer)

Unfortunately, this class method is not working as designed.

Upvotes: 0

Views: 168

Answers (2)

tomcounsell
tomcounsell

Reputation: 5081

This is already correct, just create the instance using

CustomOrder.create()

Upvotes: 1

Ngenator
Ngenator

Reputation: 11269

As you stated, your code works already. The other way to do this is to put it on the Manager

class CustomOrderManager(models.Manager):
    def create_custom_order(self):
        return self.create(product=Product.objects.create(), customer=Customer.objects.create())

class CustomOrder(models.Model):
    product = models.OneToOneField(Product)
    customer = models.ForeignKey(Customer)

    objects = CustomOrderManager()

custom_order = CustomOrder.objects.create_custom_order()

Upvotes: 1

Related Questions