Search code examples
pythondjangostringmany-to-manyfield

Django add many to many relationship from _meta.get_field


So I have the following

b = Brand.objects.create(**model_fields_and_values)
b.save()

and then I try to associate that entry with

b._meta.get_field("myfield").add(value3)

and I get the error 'ManyToManyField' object has no attribute 'add'

How can I create an association using a string and not the field ???

I dont want to use b.myfield.add(value3)


Solution

  • getattr allows you to get an attribute using the attribute name:

    getattr(b, 'myfield').add(value3)