【问题标题】:Django querying models with foreignkeyDjango 使用外键查询模型
【发布时间】:2020-08-15 11:48:10
【问题描述】:

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

我已经创建了这些模型。

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)

我想获取特定客户所下订单的状态,我还设置了用于获取客户资料视图页面的动态 url,我想在其中循环并打印出相应字段的状态。

我已经附上了我想要数据的客户资料视图页面的图像。

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.

【问题讨论】:

  • 您正在尝试获取特定客户的所有订单状态,对吧?

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


【解决方案1】:

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

# 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

【讨论】:

  • 感谢 Ejaz,我试过了,效果很好,谢谢你的帮助。
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 2020-11-15
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
相关资源
最近更新 更多