我使用python和Django框架,并且有两个具有外键关系的表,并且我想创建一个查询,其中结果包括第二个表中的字段,并使用外键将结果导出到某些JSON API中。
我想在表工作中创建一个查询,但在结果中我想基于外键添加表功能中的字段
models.py
class work(models.Model):
field_0 = models.CharField(max_length=100,blank=True, null=True)
field_1=models.CharField(max_length=100,blank=True, null=True)
class abilities(models.Model):
field_3 = models.CharField(max_length=100,blank=True, null=True)
field_4=models.CharField(max_length=100,blank=True, null=True)
field_5=models.CharField(max_length=254,blank=True, null=True)
field_fk= models.ForeignKey('work', blank=True, null=True)
views.py
def work_json(request):
work_se=serialize('json',work.objects.all())
return HttpResponse(work_se,content_type='json')
从我的角度来看json结果:
[
{
"model": "mymodel",
"pk": 1,
"fields": {
"field_0": "some value",
"field_1": "some value field 1",
}
}
……… next object
]
我需要的json结果(带有表中具有field_fk 1的字段)
[
{
"model": "mymodel",
"pk": 1,
"fields": {
"field_0": "some value",
"field_1": "some value field 1",
"field_3": "some value field 3",
"field_4": "some value field 4",
"field_5": "some value field 5",
}
……… next object
]
知道怎么做吗?
谢谢
答案 0 :(得分:0)
您建议的平面包含仅在两个模型之间存在一对一关系时才有效。对于一对多关系,您需要将Abilities
对象嵌套在Work
对象中(请参阅Python naming conventions BTW)。 Django Rest Framework可以帮助您做到这一点,给您这样的东西:
{
"id": 1,
"field_0": "data in field_0",
"abilities_set": {
{
"id": 1,
"field_3": "data in field_3",
"field_4": "data in field_4",
"field_5": "data in field_5"
},
{
"id": 2,
"field_3": "data in field_3",
"field_4": "data in field_4",
"field_5": "data in field_5"
}
}
}
答案 1 :(得分:0)
class ResourceSerializer(serializers.ModelSerializer):
class Meta:
model = Resource
fields = '__all__'
class SiteSerializer(serializers.ModelSerializer):
resources = ResourceSerializer(read_only=True, many=True) # resource is the foreign key in site
class Meta:
model = Site
fields = '__all__'
def all_sites(request):
sites = Site.objects.all()
serialize = SiteSerializer(sites, many=True)
main = {'status': True, 'msg': 'OK', 'sites': serialize.data}
return HttpResponse(json.dumps(main), content_type='application/json')
为两个模型创建模型序列化器,视图中的serialize.data
包含您要作为字典访问的字典,这就是您想要的吗?