Issue
First I am extracting the model name of the M2M field from the value I get through the loop. Then I am trying to add data to m2m table, but this AttributeError: 'ProductAttributes' object has no attribute 'm2m_model'
is coming.
attribute = ProductAttributes.objects.get(pk=pk)
for key in common_keys:
if initial[key] != new_data[key]:
# Getting m2m model in lower case
m2m_model = apps.get_model(app_label=app, model_name=key)._meta.model_name
attribute.m2m_model.add(new_data[key])
Here's the problem attribute.m2m_model.add(new_data[key])
If I directly name the field then it works fine like below:
attribute.color.add(new_data[key])
attribute.ram.add(new_data[key])
I want to make it dynamic.
Here is my model:
class ProductAttributes(models.Model):
color = models.ManyToManyField('Color')
band_color = models.ManyToManyField('BandColor')
ram = models.ManyToManyField('RAM')
vram = models.ManyToManyField('VRAM')
Thanks in advance, any help would be much appreciated.
Solution
You can work with getattr(…)
[Python-doc], but it looks like bad code design to rely that the field is the model name in lowercase:
attribute = ProductAttributes.objects.get(pk=pk)
m2m_model = apps.get_model(app_label=app, model_name=key)._meta.model_name
for key in common_keys:
if initial[key] != new_data[key]:
# Getting m2m model in lower case
getattr(attribute, m2m_model).add(new_data[key])
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.