To convert a Django model instance to a dictionary with foreign instance, you can use the following code:

def model_to_dict(instance):
    data = {}
    for field in instance._meta.fields:
        value = getattr(instance, field.name)
        if isinstance(value, models.Model):
            data[field.name] = model_to_dict(value)
        else:
            data[field.name] = value
    return data

This function recursively converts all foreign key instances to dictionaries until it reaches the end of the related object's chain.

Example usage:

my_object = MyModel.objects.get(id=1)
my_dict = model_to_dict(my_object)

This will return a dictionary with all the fields of the MyModel instance, including any foreign key relationships.

Convert Django Model Instance to Dictionary with Foreign Keys

原文地址: http://www.cveoy.top/t/topic/lMCn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录