[Django]-Django DetailView + show related record of another Model

5👍

What I do in this case is add the related object into the context data. It would be something like this:

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

2👍

Another approach is to extend DetailView with MultipleObjectMixin, as in this example:

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  

In my opinion this approach is a little less cleaner and understandable, but it has a huge advantage in reusability. It definitely has one downside: if you are using the class variable context_object_name, it will refer to the related objects list and not to the object itself (this has to do with how the inheritance chain is set up when constructing the class).

👤mp85

Leave a comment