Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn Django Model objects into a dictionary and still have their foreign keys? [duplicate]

People also ask

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

How do I override a Django model?

Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.

How does ForeignKey work in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.


obj = get_object_or_404(CustomModel,id=some_id)
my_dict = obj.__dict__

How about:

model_to_dict(instance, fields=[field.name for field in instance._meta.fields])

By explicitly naming all of the fields, it should give you the foreign key ids at least (although I haven't verified).

Note that this function does not return fields with editable=False (since it is intended for forms).


I think I had the same need as you -- I wanted a plain-and-simple dict representation of an object. the other answers posted (at the time I write) wouldn't give me that, and the serializers, while useful for their purpose, produce output with extra info I don't want, and an inconvenient structure.

Though admittedly a hack, this is giving me good mileage:

from django.core import serializers

def obj_to_dict(model_instance):
    serial_obj = serializers.serialize('json', [model_instance])
    obj_as_dict = json.loads(serial_obj)[0]['fields']
    obj_as_dict['pk'] = model_instance.pk
    return obj_as_dict

wrapping the django_model_object in a list, then accessing item 0 after parsing the json is needed because, for some reason, serializers can only serialize iterables of model objects (weird).

You'd need some extra gears to handle any kind of foreign key fields, I may post back if I end up needing to write that (unless someone else edits it in first!).

HTH for now.