[Solved]-Django – automatically create a model instance when another model instance is created

8👍

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

See the signals tutorial for more information.

👤AKX

23👍

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)
👤JPG

2👍

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)
👤jcirni

0👍

I believe the modern ways (as per the docs) are to do this during a create() class method or to write a custom manager.

https://docs.djangoproject.com/en/3.1/ref/models/instances/

👤Rob

Leave a comment