Create OneToOne instance on model creation

前端 未结 3 1994
孤街浪徒
孤街浪徒 2020-12-13 14:50

I\'m building my first django app. I have a user, and the user has a list of favourites. A user has exactly one list of favourites, and that list belongs exclusively to that

3条回答
  •  醉梦人生
    2020-12-13 15:22

    The most common way to accomplish this is to use the Django signals system. You can attach a signal handler (just a function somewhere) to the post_save signal for the User model, and create your favorites list inside of that callback.

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    from django.contrib.auth.models import User
    
    @receiver(post_save, sender=User)
    def create_favorites(sender, instance, created, **kwargs):
        if created:
            Favorites.objects.create(user=instance)
    

    The above was adapted from the Django signals docs. Be sure to read the signals docs entirely because there are a few issues that can snag you such as where your signal handler code should live and how to avoid duplicate handlers.

提交回复
热议问题