2015-01-16 67 views
0

我想返回到用戶相關記錄。 有人可以幫助我嗎?我的觀點的Django DetailView +顯示另一個模型的相關記錄

部分

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) 
... 

我怎樣才能perfome這在第一觀看UserProfileDetailView, 顯示相關的數據?

回答

2

我在這種情況下做的是將相關對象添加到上下文數據中。這將是這樣的:

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 
0

另一種方法是用MultipleObjectMixin延長DetailView,如本例:

from django.views.generic import DetailView 
from django.views.generic.list import MultipleObjectMixin 
from django.contrib.auth import get_user_model 

class DetailListView(MultipleObjectMixin, DetailView): 
    related_model_name = None 

    def get_queryset(self): 
     # a bit of safety checks 
     if not hasattr(self, "related_model_name"): 
      raise AttributeError(
       "%s.related_model_name is missing." % ( 
        self.__class__.__name,)) 
     if not self.related_object_name: 
      raise NotImplementedError(
       "%s.related_model_name must not be None." % ( 
        self.__class__.__name,)) 
     # get the object 
     obj = self.get_object() 
     # get the related model attached to the object 
     related_model = getattr(obj, "%s_set" % self.related_model_name, None) 
     # safety check if related model doesn't exist 
     if not related_model: 
      raise AttributeError(
       "%s instance has no attribute \"%s_set\"" % (
        obj.__class__.__name__, self.related_model_name) 
     # return the related model queryset 
     return related_model.all() 

    def get(self, request, *args, **kwargs): 
     self.object_list = self.get_queryset() 
     return super(DetailListView, self).get(request, *args, **kwargs) 

class UserProfileDetailView(DetailListView): 
    template_name = "perfil.html" 
    model = get_user_model() 
    slug_field = "username" 
    related_model_name = "anothermodel" 

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

在我看來這種做法是清潔少一點,可以理解的,但它在可重用性方面有巨大的優勢。它肯定有一個缺點:如果使用類變量context_object_name,它將引用相關對象列表而不是對象本身(這與構建類時如何設置繼承鏈有關)。

相關問題