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

def instance_to_dict(instance):
    data = {}
    for field in instance._meta.fields:
        value = getattr(instance, field.name)
        if isinstance(value, models.Model):
            data[field.name] = instance_to_dict(value)
        elif isinstance(value, datetime.datetime):
            data[field.name] = value.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(value, datetime.date):
            data[field.name] = value.strftime('%Y-%m-%d')
        else:
            data[field.name] = value
    for related_object in instance._meta.related_objects:
        accessor_name = related_object.get_accessor_name()
        if hasattr(instance, accessor_name):
            related_instances = getattr(instance, accessor_name).all()
            if related_instances:
                data[accessor_name] = [instance_to_dict(related_instance) for related_instance in related_instances]
    return data

This function recursively converts all foreign key instances to dictionaries as well. You can use it like this:

instance_dict = instance_to_dict(my_instance)

Note that this code assumes that all related objects are either many-to-one or many-to-many relationships. If you have one-to-one relationships, you'll need to adjust the code accordingly.

Convert Django Model Instance to Dictionary with Foreign Keys

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

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