gpt4 book ai didi

Django DetailView + 显示另一个Model的相关记录

转载 作者:行者123 更新时间:2023-12-04 02:03:56 25 4
gpt4 key购买 nike

我想返回用户相关记录。有人可以帮助我吗?

我的部分观点

class UserProfileDetailView(DetailView):
model = get_user_model()
slug_field = "username"
template_name = "perfil.html"

def get_object(self, queryset=None):
user = super(UserProfileDetailView, self).get_object(queryset)
UserProfile.objects.get_or_create(user=user)
return user


Something like a old way>
def my_view(request, slug):
var = get_object_or_404(Model, slug=slug)
xxx = AnotherModel.objects.filter(var=var)
...

我如何在第一个 View UserProfileDetailView 中执行此操作,显示相关数据?

最佳答案

在这种情况下,我所做的是将相关对象添加到上下文数据中。它会是这样的:

class UserProfileDetailView(DetailView):
model = get_user_model()
slug_field = "username"
template_name = "perfil.html"

def get_context_data(self, **kwargs):
# xxx will be available in the template as the related objects
context = super(UserProfileDetailView, self).get_context_data(**kwargs)
context['xxx'] = AnotherModel.objects.filter(var=self.get_object())
return context

关于Django DetailView + 显示另一个Model的相关记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com