gpt4 book ai didi

django - 在django模型保存方法中获取ManytoMany字段的选定值

转载 作者:行者123 更新时间:2023-12-02 05:46:05 26 4
gpt4 key购买 nike

我正在尝试从 Django admin 将数据添加到表BillRecord。我需要访问模型saveManytoMany字段的选定值方法并需要根据 ManytoMany 字段的选定对象执行一些逻辑。

class ProductType(BaseApplicationModel):
name = models.CharField(max_length=128)

class Product(BaseApplicationModel)
type = models.ForeignKey(ProductType,related_name="products")

class BillRecord(BaseApplicationModel):
products = models.ManyToManyField(Product, related_name="billrecords")

def save(self, *args, **kwargs):
super(BillRecord, self).save(*args, **kwargs)
for product in self.products.all():
print product

在代码中,当我尝试打印产品的值时,它给我 billing.Product.Noneself.products.all() 返回空查询集

我需要获取 ManyToMany 字段选择框中所选对象的 ID。 picture

最佳答案

问题在于,当 Product 与您的 BillRecord 实例关联时,它并不总是保存。对于多对多关系,您可以先保存任一对象。正确的处理方法是使用 m2m-changed signal :

Sent when a ManyToManyField is changed on a model instance. Strictly speaking, this is not a model signal since it is sent by the ManyToManyField, but since it complements the pre_save/post_save and pre_delete/post_delete when it comes to tracking changes to models, it is included here.

所以你应该尝试如下操作:

from django.db.models.signals import m2m_changed

...your models here...

def products_changed(sender, **kwargs):
# Do something here
pass

m2m_changed.connect(products_changed, sender=BillRecord.products.through)

关于django - 在django模型保存方法中获取ManytoMany字段的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44155519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com