【问题标题】:How to get selected data from different table in Django database and return json to web client如何从 Django 数据库中的不同表中获取选定的数据并将 json 返回到 Web 客户端
【发布时间】:2018-08-12 23:10:48
【问题描述】:

view.py中有Company、product、customer表,product.id、customer.id是Company类的forighen key,如何获取选中的数据。

like 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】:

    首先,您的模型应该在您的 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

    【讨论】:

    • 嗨 Shahzeb Qureshi,这是在 view.py 中添加的代码?company = Company.objects.filter(id=1).select_related('customer')
    • 你知道我如何从 Web 客户端获取 json 数据吗?比如在 127.0.0.1:8000/static/list.html 中获取 json 数据
    • 是的,您的 views.py 将有一个函数,其中包含公司查询集代码和其他代码。您的 urls.py 将定义一个 url 来指向 views.py 中的函数。您的函数将返回 json 数据,您可以使用 ajax 在 html 文件中调用它
    • 它正在工作! @action(detail=True, method=["GET"]) def get_queryset(self): queryset = Notification.objects.filter(name=self.request.user).select_related('product_id') return queryset
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2012-12-12
    • 2021-04-22
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多