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
- How to filter multiple fields with list of objects
- How to programmatically generate celerybeat entries with celery and Django
- ImportError: No module named bootstrap3
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)
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.
👤Rob
- Volley requests not working with Django Sessions
- Django-cms for multiple websites
- How to make a customizable user survey in Django
- How to add namespace url to a django-rest-framework router viewset
- Twitter bootstrap typeahead custom keypress ENTER function
Source:stackexchange.com