gpt4 book ai didi

django - 创建实例时如何更新 ManyToManyField

转载 作者:行者123 更新时间:2023-12-03 09:27:20 27 4
gpt4 key购买 nike

我想在创建实例时更新字段,我尝试过 signals但对 ManyToManyField 来说似乎很复杂

class MobileCustomer(models.Model):
customer = models.CharField(max_length=30)
phone = models.CharField(max_length=13)
mobile = models.ManyToManyField(MobileStorage,through='SelectMobile')

class SelectMobile(models.Model):
mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE)
item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
imei = models.ManyToManyField(Imei)

class MobileStorage(models.Model):
mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()

class Mobile(models.Model):
mobile_name = models.CharField(max_length=40,unique=True)

class Imei(models.Model):
imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True)
mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE)
active = models.BooleanField(default=True)

我想更新 Imei 中的事件字段型号当 MobileCustomer创建!?
我在我的 CreateView form_valid 中试过这个
imei = Imei.objects.filter(selectmobile__item=self.object).update(active=False)
print(imei)

它打印了 0 ?
每当在 createview 中创建实例时,如何使用信号或 update() 使其工作

最佳答案

查找问题。 mobile 查找到 MobileStorage,然后 mobilecustom 查找到 MobileCustomer。

def form_valid(self, form):
# self.object = None
super().form_valid(form)
# self.object = a instance of MobileCustomer
imei = Imei.objects.filter(mobile__mobilecustomer=self.object).update(active=False)
print(imei)

关于django - 创建实例时如何更新 ManyToManyField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62466783/

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