How can I turn Django Model objects into a diction

2020-02-10 02:04发布

In my Django app, how can I turn objects from Models into a dictionary that includes the foreign-key references of the Model object?

When I try this:

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])

The resulting dictionary only has the direct fields. I would like to also get the foreign keys related to the Model object. How can I do this?

6条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-10 02:34

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).

查看更多
放我归山
3楼-- · 2020-02-10 02:38

None of the other answers quite worked for me. This, however, seemed to do the trick.

def model_to_dict(instance, include=None, exclude=None):
    fields = instance._meta.concrete_fields
    if include is not None:
        return {f.attname: getattr(instance, f.attname) for f in fields if f.name in include}
    if exclude is not None:
        return {f.attname: getattr(instance, f.attname) for f in fields if f.name not in exclude}
    return {f.attname: getattr(instance, f.attname) for f in fields}
查看更多
神经病院院长
4楼-- · 2020-02-10 02:39

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-02-10 02:42
obj = get_object_or_404(CustomModel,id=some_id)
my_dict = obj.__dict__
查看更多
家丑人穷心不美
6楼-- · 2020-02-10 02:42

You may want to have look at Django serialization if you want to work with related models.

查看更多
ら.Afraid
7楼-- · 2020-02-10 02:43

I imagine that you've already solved this problem for your case, but I found some info as I was searching for similar solutions. I wanted to be able to access objects and their fields/attributes in a template. I am just learning django.

What I finally read-up on was the 'Generic Display Views', which seem to be able to send an object instance or a queryset of objects along to a template. Then you can access the objects like the model.field, or even if it's a foreignkey field, model.foreignmodel.foreignmodelfield.

So it's been pretty useful for me. This was after I built a bunch of custom 'to-dict' methods in different class managers. This helped me a lot. But you'll have to read up on the Generic Views and how to customize them to really get the details you want.

-Matt

查看更多
登录 后发表回答