Django:如何从多对多字段中获取对象?

Django: How to get an object from many to many field?

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

我创建了一个模型 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'

谁能告诉我我的代码哪里做错了?

谢谢

基于所有评论:

首先阅读PEP8 and Django coding style

要修复您当前的错误,您可以使用 ManyRelatedManager 的方法 all,例如它可以如下所示:

@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
        )