Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Django - Access field by iterating over field list

I am storing all many to many fields on an object using this -

m2m_fields = list(model_source_obj._meta.many_to_many)

I want to iterate over this list to make changes to another object of the same type. I have written the code for it as such -

for field in m2m_fields:
    model_target_obj.field.add(**something)

However, I keep getting the error model_target_obj class type has no attribute 'field'. How can I fix this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're not accessing the field, you're accessing the (non-existent) literal attribute called "field".

You could use getattr:

obj = getattr(model_target_obj, field)
obj.add(**something)

But I suspect that there are better ways to do whatever you are trying to do.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!