Get selected values of ManytoMany field in django model save method

Viewed 2479

I am trying to add data to a table BillRecord from Django admin.I need to access selected values of ManytoMany field in model save method and need to do some logic depending upon the selected objects of ManytoMany field.

class ProductType(BaseApplicationModel):
   name = models.CharField(max_length=128)

class Product(BaseApplicationModel)
   type = models.ForeignKey(ProductType,related_name="products")

class BillRecord(BaseApplicationModel):
    products = models.ManyToManyField(Product, related_name="billrecords")

    def save(self, *args, **kwargs):
       super(BillRecord, self).save(*args, **kwargs)
       for product in self.products.all():
          print product

In the code when I tried to print the values of product it gives me billing.Product.None that is self.products.all() returns empty queryset

I need to get the ID's of the selected objects in the ManyToMany field select box. picture

2 Answers

There are three kind of action in m2m: add, remove, clean

the signal @receiver(m2m_changed, sender=Model.manytomanyfield.through) iterate actions:

first:

pre-remove and post-remove: if some objects are removed from your manytomanyfield then to pre-add, here you can access to your selected (new) values and to the instance (with the removed objects of manytomanyfield). You could write something like that to get them:

@receiver(m2m_changed, sender=ProductVariation.combination.through)

def check_attribute(sender, **kwargs): instance = kwargs['instance']

import pdb; pdb.set_trace()
if kwargs['action'] == 'pre_add':
    if kwargs.get('pk_set'):
        product_attributes = instance.combination.all() | \
                             ProductAttribute.objects.filter(id__in=kwargs.get('pk_set'))
        groups_count = product_attributes.values('attribute').annotate(Count('id'))
        for group in groups_count:
            if group.get('id__count', 0) > 1:
                attribute_name = Attribute.objects.get(id=group['attribute'])
                rai
Related