Django使用Foreignkey查询模型

时间:2020-08-15 11:48:10

标签: django django-models django-views python-3.7

我正在创建一个客户管理项目,在此我想查询一些与外键有关的模型。

我已经创建了这些模型。

from django.db import models


class Customer(models.Model):
    name = models.CharField(max_length=250, null=True)
    phone = models.CharField(max_length=10, null=True)
    email = models.CharField(max_length=250, null=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    # to get name as string on behalf of "Customer Object 1" in DB.
    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=250, null=True)
    
    def __str__(self):
        return self.name


class Product(models.Model):
    # To make a dropdown menu to choose category.
    CATEGORY = (
        ('Indoor', 'Indoor'),
        ('Out Door', 'Out Door'),
    )

    name = models.CharField(max_length=250, null=True)
    price = models.FloatField(null=True)
    category = models.CharField(max_length=250, null=True, choices=CATEGORY)
    description = models.CharField(max_length=250, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name
class Order(models.Model):
    # To make a dropdown menu to choose status.
    STATUS = (
        ('Pending', 'Pending'),
        ('Out for Delivery', 'Out for Delivery'),
        ('Delivered', 'Delivered'),
    )

    customer = models.ForeignKey(Customer, null=True,
                                 on_delete=models.SET_NULL)
    product = models.ForeignKey(Product, null=True,
                                on_delete=models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=250, null=True, choices=STATUS)

Views.py

from django.shortcuts import render
from .models import *


def home(request):
    customers = Customer.objects.all()
    orders = Order.objects.all()

    total_customers = customers.count()
    total_orders = orders.count()
    delivered = orders.filter(status='Delivered').count()
    pending = orders.filter(status='Pending').count()

    front_end_stuff = {'customers': customers, 'orders': orders,
                       'total_customers': total_customers, 'total_orders': total_orders,
                       'delivered': delivered, 'pending': pending,
                       }

    return render(request, 'accounts/dashboard.html', context=front_end_stuff)


def products(request):
    products_ = Product.objects.all()

    return render(request, 'accounts/products.html', context={'products': products_})


def customer(request, pk):
    customers = Customer.objects.filter(id=pk)
    orders = Order.objects.filter(id=pk)
    customer_products = Product.objects.filter(id=pk)

    total_orders = orders.count()

    front_end_stuff = {'customers': customers, 'orders': orders,
                       'total_orders': total_orders, 'customer_products': customer_products
                       }

    return render(request, 'accounts/customer.html', context=front_end_stuff)

我想获取特定客户下达的订单状态,我还设置了用于获取客户资料查看页面的动态网址,并希望在其中循环浏览并在相应字段中打印出状态。

我已经在我想要数据的客户个人资料查看页面上附加了图像。

customer_profile_view_page

我尝试了一个在互联网上发现的查询:

customers = Customer.objects.filter(id=pk)
status = customers.order_set.all()

但是我得到一个错误

AttributeError:“ QuerySet”对象没有属性“ order_set”

我正在使用:

  • Windows 10,
  • Python 3.7,
  • Django 3.0.7。

1 个答案:

答案 0 :(得分:0)

要获取客户所有订单的列表,可以尝试-

# this will give the list of orders for customer with id = pk
orders = Order.objects.filter(customer__id=pk) # it's a double underscore

您可以迭代每个订单以获取状态-

for order in orders:
    print(order.status)

或者按照您尝试的方式,使用.get代替.filter

customer = Customer.objects.get(id=pk) # the customer has to be present with this id else it will give an exception.
orders = customer.order_set.all()

Doc

相关问题