每次创建父对象时都创建外键对象的实例

时间:2019-03-07 04:46:00

标签: python mysql django django-models foreign-keys

我想创建一个Cart对象,该对象链接到数据库中的User模型。每次创建用户时,都希望创建一个链接的购物车(在数据库中)。 有什么建议么?我尝试将其链接到用户ID,但没有任何乐趣。

models.py

from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save

# Create your models here.


class Product(models.Model):
    name = models.CharField(max_length=50)
    desc = models.CharField(max_length=50)
    img = models.FileField()
    created = models.DateField()
    num_stars = models.IntegerField()


class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,to_field='id', null=True)
    content = models.CharField(max_length=50)
    last_update = models.DateTimeField()

1 个答案:

答案 0 :(得分:2)

创建用户时,只需让接收方处理购物车的创建

from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.utils import timezone
class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,to_field='id', null=True)
    content = models.CharField(max_length=50,null=True,blank=True)
    last_update = models.DateTimeField(default=timezone.now)
@receiver(post_save, sender=User)
def create_user_cart(sender, instance, created, **kwargs):
    if created:
        Cart.objects.get_or_create(user=instance)