How to set dict key as dynamic field name to add value m2m fields in Django

I want to set the m2m field name from the dictionary key dynamically so that I don't have to type each field name separately. Any help would be much appreciated.

instance = ProductAttributes.objects.create(device_type=1, manufacturer=2, created_by=request.user)

device_dict = {
  'watch_series': WatchSeries.objects.get(series=mergedict['watch_series']),
  'watch_size': WatchSize.objects.get(size=mergedict['watch_size']),
  'color': Color.objects.get(id=mergedict['color']),
  'band_color': BandColor.objects.get(color=mergedict['band_color']), 
  'watch_connectivity': 1 if mergedict['is_gps'] == True else 2
 }

This is how I'm trying to add m2m field name after instance

for key, val in device_dict.items():
    instance._meta.get_field(key).add(val)

I'm getting this error:

AttributeError: 'ManyToManyField' object has no attribute 'add'

You don't have to get field from Meta, you can access it directly on instance:

for key, val in device_dict.items():
    getattr(instance, key).add(val)
Back to Top