我试图访问模板中的相关数据,但却没有得到任何结果。
模型
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Product(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
price = models.PositiveBigIntegerField()
discount = models.PositiveBigIntegerField(default=0)
inventory = models.PositiveBigIntegerField(default=1)
last_update = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
return self.title
class Image(models.Model):
image = models.ImageField()
product = models.ForeignKey(to=Product,on_delete=models.CASCADE)
class Cart(models.Model):
STATUS = [
(0,"pending payment"),
(1,"paid")
]
status = models.SmallIntegerField(choices=STATUS,default=0)
user = models.ForeignKey(to=User,on_delete=models.CASCADE)
created = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return f"{self.user} - {self.status}"
@receiver(post_save,sender=Cart)
def cart_post_save(sender, instance, created, *args, **kwargs):
if created and instance.status == 1 :
Cart.objects.create(user=instance.user)
class Order(models.Model):
product = models.ForeignKey(to=Product,on_delete=models.CASCADE)
count = models.PositiveIntegerField(default=0)
cart = models.ForeignKey(to=Cart,on_delete=models.CASCADE)
def __str__(self) -> str:
return f"{self.product}"
视图
from django.views import generic
from . import models
from django.http import JsonResponse,HttpResponseBadRequest,HttpResponse
class ProductsList(generic.ListView):
"""return list of all products and template name is prudoct_list.html"""
model = models.Product
paginate_by = 30
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class ProductsDetail(generic.DetailView):
"""return a product and template name is prudoct_detail.html"""
model = models.Product
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
基础.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>online-shop</title>
</head>
<body>
<nav>
{% if request.user.is_anonymous %}
{% else %}
{{request.user}}
<form method="post" action="{% url 'logout' %}">
{% csrf_token %}
<button type="submit">logout</button>
</form>
<a href="{% url 'cart' %}">cart</a>
{% endif %}
</nav>
<script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
{% block content %}
{% endblock content %}
</body>
</html>
产品详细信息.html
{% extends "base.html" %}
{% block content %}
{% for image in object.image_set.all %}
<img src="{{image.image.url}}" alt="">
{% endfor %}
<div>title : {{object.title}}</div>
<div>description : {{object.description}}</div>
<div>price : {{object.price}}</div>
<div>discount : {{object.discount}}</div>
<div>last_update : {{object.last_update}}</div>
**{{object.order_set.first}}** # returns None
{% endblock content %}
我希望首先订购,{{object.order_set.first}}
并且 RelatedManager 对图像也能正常工作。
{% for image in object.image_set.all %}
<img src="{{image.image.url}}" alt="">
{% endfor %}
但对于订单我只得到 None 。product_detail 中的输出是:
标题:test123 描述:此处有一些文字 价格:12345 折扣:0 最后更新:2024 年 8 月 9 日,下午 7:03 无
如果我将{{object.order_set.first}}更改为 {{object.order_set}} 输出将是
标题:test123 描述:此处有一些文字 价格:12345 折扣:0 最后更新:2024 年 8 月 9 日,下午 7:03 stor.Order.None
更新
{{object.order_set.all}}
返回 -><QuerySet []>
并且
{% for order in object.order_set.all %}
{{order}}
{% endfor %}
由于为<QuerySet []>
空,因此不返回任何内容
python 版本 -> 3.10.11 Django 版本 -> 5.1
您可以获得
None
所有相关经理的信息。您可以使用{{ object.order_set.all }}
它将其转换为查询集,以打印(部分)项目。但
{{ object.order_set }}
这样做根本没什么意义,即使它会打印记录,也会生成相当丑陋的记录。<QuerySet [order1, order2]>
枚举关系并正确格式化顺序: