Serialize django model with foreign key models

前端 未结 2 1739
你的背包
你的背包 2021-01-19 10:42

How to serialize Django model in json format if I want to include foreign key models fields?

If I have:

class Model1(models.Model):
    name=models.C         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 11:19

    it's been sometimes that i didn't work on django but is this work for you ?

    import simplejson as json
    
    data = Model1.objects.get(pk=some_id)
    
    to_dump =  {'pk': data.pk, 'name':data.name, 
               'fields':{'field_1':data.child.field_1, 
                         'field_2':data.child.field_2 
                        }
                }
    
    json_data = json.dumps(to_dump)
    

提交回复
热议问题