如何根据另一个模型的id筛选模型字段中的某些项目



这是一个奇怪的问题

class Post(models.Model):
name = models.CharField(max_length=200)
class PostKey(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.post.name + " | " + self.name

我正在尝试使用详细信息视图,以便它显示Post模型的详细信息,并显示与post.id具有相同id的PostKey的列表(想不出任何其他名称)。我使用ForeignKey创建了一个与Post模型的一对多关系。

这是我的观点:

from django.shortcuts import render 
from django.views.generic import TemplateView, DetailView
from .models import Post, PostKey
class TestView(TemplateView):
template_name = "test.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["posts"] = Post.objects.all()
return context
class PostDetailView(DetailView, Post):
template_name = "test2.html"
model = Post

def get_context_data(self, **kwargs ):
context = super().get_context_data( **kwargs)

context['details'] = PostKey.objects.filter(id= Post.id)
return context

但是当我运行这个代码时,它会显示这样的内容:

TypeError at /post/2
Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x03F88478>.

我已经尝试添加int(Post.id),但它仍然不起作用。

以下是为上述视图渲染的模板。

{% for detail in details %}   
{{detail.name}}
{% endfor %}

如有任何帮助,将不胜感激

您使用进行过滤

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['details'] = PostKey.objects.filter(post=self.object)
return context

或带有:

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['details'] = self.object.postkey_set.all()
return context

您编写的代码

context['details'] = PostKey.objects.filter(id= Post.id)

不起作用,因为Post是模型类,而不是模型实例,这意味着Post.id是该类的模型字段定义,而不是您要查找的Post实例的值;CCD_ 10中的实例在CCD_。

此外,您可能希望搜索所有以self.object为其父级的PostKey实例,而不是那些与父级具有相同ID的实例;您需要使用字段PostKey.post(它是父Post的ForeignKey)进行筛选。


您可能需要使用Post实例(在self.object中)来筛选所有以self.object为其父对象的PostKey对象。

class PostDetailView(DetailView):
template_name = "test2.html"
model = Post

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['details'] = PostKey.objects.filter(post=self.object)
# or also the way @WillemVanOnsem suggested in his answer
# context['details'] = self.object.postkey_set.all()
return context

你展示的模板代码似乎很好:

{% for det in details %}   
{{ det.name }}
{{ det }}          <!-- this will use method PostKey.__str__() -->
{% endfor %}

此外,为什么要从Post(您有class PostDetailView(DetailView, Post):)继承类?这似乎不对,在这种情况下,它应该只是从DetailView继承。

最新更新