update for manytomany field

若如初见. 提交于 2020-06-23 12:50:25

问题


i want to to update field whenever an instance been created i tried signals but it seems complicate to 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)

i want to update active field in Imei model when MobileCustomer created !? i tried this in my CreateView form_valid

imei = Imei.objects.filter(selectmobile__item=self.object).update(active=False)
print(imei)

and it printed 0 ? how to make it work either using signals or update() whenever an instance created inside createview


回答1:


Using .filter() will return a list. You want to use something like a .get() or the following get or 404 to get a single object.

imei = get_object_or_404(Imei, pk=imei_id)
imei.active = False
imei.save()

If you already have the object which is self.object you can use

imei = self.object
imei.active = False
imei.save()


来源:https://stackoverflow.com/questions/62466783/update-for-manytomany-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!