art_cs
art_cs

Reputation: 791

how to get each id of each selected in M2M djnago

i want to get the ID of selected imeis

class Mobile(models.Model):
    mobile = models.CharField(max_length=20,unique=True)
    quantity = models.IntegerField()
    imei = models.ManyToMany(Imei,on_delete=models.CASCADE)

class Imei(models.Model):
    imei = models.CharField(max_length=13,unique=True)
    active = models.BooleanField(default=True)

if i selected 10 imei's i want to get 10 ID's of selected imeis!? i tried this ways but no one worked !

instance.imei__id 
instance.imei.id
instance.imei_id

i appreciate your helps

Upvotes: 1

Views: 65

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

instance.imei is a manager. You can access the Imei objects with:

instance.imei.all()  # QuerySet of Imei objects

Or if you are only interested in the primary keys (pks) of the Imei objects:

instance.imei.values_list('pk', flat=True)  # QuerySet of Imei primary keys

EDIT: You can update all values with:

instance.imei.all().update(active=False)

You can for example run it in a CreateView with:

class MyCreateView(CreateView):
    model = Mobile
    # …

    def form_valid(self, form):
        result = super().form_valid(form)
        self.object.imei.all().update(active=False)
        return result

or for a "nested" ManyToManyField:

class MyCreateView(CreateView):
    model = Mobile
    # …

    def form_valid(self, form):
        result = super().form_valid(form)
        Imei.objects.filter(selectmobile__item=self.object).update(active=False)
        return result

Upvotes: 1

Related Questions