Django - automatically create a model instance when another model instance is created

Method-1: Use Django's post_save signal (as @AKX said)

from django.contrib.auth import get_user_model


@receiver(post_save, sender=get_user_model())
def create_user_cart(sender, instance, created, **kwargs):
    if created:
        Cart.objects.create(user=instance)


Method-2: Override the save() method of your User model or extended Usermodel

class MyUserModel(....):
    # your code
    def save(self,*args,**kwargs):
        created = not self.pk
        super().save(*args,**kwargs)
        if created:
            Cart.objects.create(user=self)

Use a Django post_save signal hooked up to the User model.

See the signals tutorial for more information.


override save method, signals are harder to read/track through multiple files and are synchronous.

https://lincolnloop.com/blog/django-anti-patterns-signals/

class Pizza(models.Model):
    has_pepperoni = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        created = self.pk is None
        super(Pizza, self).save(*args, **kwargs)
        if created and self.has_pepperoni:
            ToppingSales.objects.filter(name='pepperoni').update(
                units_sold=F('units_sold') + 1)           


class ToppingSales(models.Model):
    name = models.CharField(max_length=100, unique=True)
    units_sold = models.PositiveIntegerField(default=0)

Tags:

Django