如何从Django数据库中的不同表中获取选定的数据并将json返回给Web客户端

问题描述 投票:0回答:1

我在view.py中有公司,产品,客户表,而product.id,customer.id是公司类中的forighen键,如何获取所选数据。

比如sql(select * from Company,customer,product where Company.customer_id = customer.id and company.product_id = product.id)并让它返回json,这样在客户端可以得到json数据?

以及如何在Web客户端中使用json数据?

我是Django的新手,你可以帮我解决这个问题吗?

class Company(models.Model):
id = models.IntegerField(blank=True, primary_key=True)
customer_id = models.IntegerField(blank=True, null=True)
product_id = models.IntegerField(blank=True, null=True)

class product(models.Model):
id = models.IntegerField(blank=True, primary_key=True)
name = models.TextField(blank=True, null=True)

class customer(models.Model):
id = models.IntegerField(blank=True, primary_key=True)
name = models.TextField(blank=True, null=True)
django django-models django-templates django-views renderer
1个回答
0
投票

首先,您的模型应该在您的django应用程序的models.py文件中。在Django中,使用models.ForeignKey引用外键字段,https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey在此处记录

您还需要确定哪个模型将引用哪个外键。像公司一样可以拥有许多客户和产品,因此公司将成为产品和客户模型的外键。

在您获取客户详细信息后的视图中,您将使用这样的代码

company = Company.objects.filter(id=1).select_related('customer')

选择相关的文档在这里给出https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related

然后,下一步是将company查询集序列化为json https://docs.djangoproject.com/en/dev/topics/serialization/#serialization-formats-json

© www.soinside.com 2019 - 2024. All rights reserved.