Search code examples
djangodatabasedjango-modelsforeign-keysclass-method

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.


Solution

  • This is already correct, just create the instance using

    CustomOrder.create()