0

I am working with a Django model which has a one-to-one relationship, and I wonder if I am doing this the best possible way. To give you some context, this are the involved classes with their cardinal relationships.

Affiliate (1)----(1) Account

class Affiliate(models.Model):
    uid = models.CharField(_('Uid'), max_length=128, blank=True, null=True)
    [...]

class Account(models.Model):
    affiliate = models.OneToOneField(Affiliate, on_delete=models.CASCADE) # Here it goes.
    [...]

I did consider joining both Affiliate and Account in the same object, but that just does not seem right. They are different model entities. I actually use them always separately, except just in one place. When I create an affiliate for any given Organization, that Affiliate must have an account created with it.

So... what I would like to ask is: Is there a better way of creating both entities at the same time, other tan creating both and relating them? This is the code in my view (post for the AffiliateModelForm)

    form = AffiliateForm(request.POST)
    if form.is_valid():
        affiliate = form.save()
        account = Account()
        account.affiliate = affiliate
        account.save()

Edit: Should I override the form.save() method? Is that it?

Edit 2: Forgot to clarify. AffiliateForm has the full Affiliate model's fields and it is used for editing the Affiliate as well, so overriding AffiliateForm's save method is as good as overriding Affiliate's save method.

coya
  • 264
  • 2
  • 15

1 Answers1

1

I think the approach you've described is totally fine, though an alternative approach, especially since you're not putting any data from the form into the account, would be to create the Account object in a pre_save / post_save signal on the Affiliate.

If you use signals, then you also handle if affiliates are created outside of this particular form, for example, in the Django admin or using another form.

https://docs.djangoproject.com/en/dev/topics/signals/

There are also some alternative answers, such as passing multiple forms to one template, in this related question: Django: multiple models in one template using forms.

Community
  • 1
  • 1
Taylor D. Edmiston
  • 12,088
  • 6
  • 56
  • 76