[Django]-How to pass ForeignKey in dict to create Model object. Django

3👍

You can use the place_id instead, this is the "twin field" Django creates that is stored in the database, and stores a reference (usually the primarh key) to the target model, given of course such Place already exists:

user_details = [
    UserDetails(name=record['name'], place_id=record['place'])
    for record in list_of_records
]
UserDetails.object.bulk_create(user_details)

Here the list_of_records is thus your list of dictionaries. We can make use of .bulk_create(…) [Django-doc] to add all UserDetails in a small number of insert queries.

3👍

This seems to be working:

def model_to_dict_wfk(modelobj):
    opts = modelobj._meta.fields
    modeldict = model_to_dict(modelobj)
    for m in opts:
        if m.is_relation:
            foreignkey = getattr(modelobj, m.name)
            if foreignkey:
                try:
                    modeldict[m.name] = foreignkey
                except:
                    pass
    return modeldict

then use the returned dictionary in the create classmethod

@classmethod
def create(cls, vals):
    obj = cls(**vals)
    obj.save()
    return obj

Leave a comment