问题
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