Django:如何从多领域获取对象?

时间:2019-02-08 13:35:46

标签: django django-models django-signals

我正在为我的电子商务应用程序创建数字产品。

我创建了一个Product_activation模型,以在用户订阅该产品时激活特定产品

我已经执行以下操作:

class Profile(models.Model):
   date = models.DateTimeField(auto_now_add=True)
   full_Name = models.CharField(max_length=32,blank=True)
   name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
   e_mail = models.EmailField(max_length=70,blank=True)
   subscribed_products = models.ManyToManyField(Product,related_name='products_subscribed',blank=True)

class Product(models.Model):
   title        = models.CharField(max_length=32)
   price        = models.DecimalField(default=10000.00,max_digits=10,decimal_places=2)

class Product_activation(models.Model):
   user         = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
   product     = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='product_activate')
   activate    = models.BooleanField(default=False)

我在下面的信号中创建了此信号:

@receiver(pre_save, sender=Profile)
def product_activation(sender,instance,*args,**kwargs):
    if instance.subscribed_products:
        Product_activation.objects.update_or_create(
            User=instance.name,
            product=instance.subscribed_products,
            activate=False,
            deactivate=True
        )

但是在product=instance.subscribed_products行代码中有问题。

这给我以下错误消息:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager'

谁能告诉我我在代码中做错了什么?

谢谢

1 个答案:

答案 0 :(得分:4)

基于所有评论:

首先阅读PEP8Django coding style

要解决当前错误,可以使用all的方法ManyRelatedManager,例如,它看起来像:

@receiver(pre_save, sender=Profile)
def product_activation(sender,instance,*args,**kwargs):
    for product in instance.subscribed_products.all():
        Product_activation.objects.update_or_create(
            User=instance.name, product=product, activate=False, deactivate=True
        )