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

219
Views
django pass field-name as variable in get_or_create

I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary)

Like so:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value)
        print ('created? ',created)
        return rem_obj

The above wont work since it would look for 'field_to_lookup' as the key.

This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This post helped. Now passing the field-value pair as dict which allows passing variables for field names. Here's the code:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(**{field_to_lookup:cell_value})
        print ('created? ',created)
        return rem_obj

Alternatively, I could directly just pass the dict to the function.

about 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!