[Answer]-Getting values from Django model

1👍

If you want to pull all related values by default, you can do the following:

def default(self, obj):
    if isinstance(obj, models.Model):
        d = model_to_dict(obj)  # here I'd like to pull some related values
        for field in obj._meta.fields:
            if field.rel: # single related object
                d[field.name] = model_to_dict(getattr(obj, field.name))

    return json.JSONEncoder.default(self, obj)

This will go one level deep for single related objects, but not for many-to-many relations or reverse foreign keys. Both are possible, but you’ll have to find out which methods/attributes on obj._meta return the specific fields.

If you only want to retrieve specific fields, you’ll have to manually specify and fetch these fields.

👤knbk

Leave a comment