Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update ManyToManyField while an instance been created

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

like image 812
art_cs Avatar asked Jun 19 '20 09:06

art_cs


Video Answer


2 Answers

lookup problem. mobile lookup to MobileStorage, then mobilecustomer lookup to 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)
like image 194
Blackdoor Avatar answered Mar 06 '23 22:03

Blackdoor


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)
like image 32
ruddra Avatar answered Mar 06 '23 22:03

ruddra