简体   繁体   中英

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)

getattr允许您使用属性名称获取属性:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM