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
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)
I think the relationship you are looking for is: Imei > MobileStorage > SelectMobile > MobileCustomer
. You can try like this:
imei = Imei.objects.filter(mobile__selectmobile__item=self.object).update(active=False)
print(imei)
post_save
signal example:
@receiver(post_save, sender=MobileCustomer)
def do_something(sender, instance, created, **kwargs):
if created:
imei = Imei.objects.filter(mobile__selectmobile__item=instance).update(active=False)
print(imei)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With