Charlesliam
Charlesliam

Reputation: 1313

Is there a short way to do Django objects.create()

Newbie here. I happen to have a create object with more than 50 fields, Is there a short way to write a create object? Any suggestion is really appreciated. Thanks

SOA_detail.objects.create(
            soa                 =instance, 
            sitename            =rec_fields['sitename'], 
            site_addr           =rec_fields['site_addr'], 
            call_sign           =rec_fields['call_sign'], 
            no_years            =rec_fields['no_years'], 
            channel             =rec_fields['channel'], 
            ppp_units           =rec_fields['ppp_units'], 
            rsl_units           =rec_fields['rsl_units'], 
            freq                =rec_fields['freq'], 
            ...
            duplicate_fee       =rec_fields['duplicate_fee'])

Ans. After a guide from jproffitt. Here's what I did. With the assumption of: header_name =[] is a dynamic listing of field names. SOA_detail is my model. soa_detail = [] is the values.

   for i in range(len(header_name)):
       for model_field in SOA_detail._meta._fields():
           # check every header_name if it is in model field name
           if header_name[i] == model_field.name:
               # update dict if found
               rec_fields[header_name[i]] = soa_detail[i]  
   SOA_detail.objects.create(soa=instance, **rec_fields)

This is much better than my original script consist of almost 100 lines.

Upvotes: 1

Views: 113

Answers (1)

jproffitt
jproffitt

Reputation: 6355

If rec_fields is a dictionary with all the model fields as keys, you can just do SOA_detail.objects.create(soa=instance, **rec_fields)

Upvotes: 2

Related Questions