简体   繁体   中英

Django - how to pass filtered querysets to Detailview

I have Client, servers, users models. In the Client Detailview i would like to display the servers and users that belong to that company. How do I filter that?

models.py

class Client(models.Model):
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name

class Server(models.Model):
    company = models.ForeignKey(Client, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name

class User(models.Model):
    company = models.ForeignKey(Client, verbose_name="Company", on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    def __str__(self):
        return self.first_name + ' ' + self.last_name

views.py

class clientdetails(LoginRequiredMixin, DetailView):
template_name = 'myapp/clientdetails.html'

def get_queryset(self):
    return Client.objects.all()

def get_context_data(self, **kwargs):
    context = super(clientdetails, self).get_context_data(**kwargs)
    context['servers'] = Server.objects.filter(** servers belonging to that client **)
    context['users'] = User.objects.filter(** servers belonging to that client **)
    return context

How do I achieve this?

If you want this to be a general use case ie all objects retrieved from the server need to be for a specific client. You can take a look at using limit-choices-to

class ClientDetails(LoginRequiredMixin, DetailView):
    template_name = 'myapp/clientdetails.html'
    model = Client

    def get_context_data(self, **kwargs):
        client = self.object
        context = super(ClientDetails, self).get_context_data(**kwargs)
        context['servers'] = Server.objects.filter(company=client)
        context['users'] = User.objects.filter(company=client)
        return context

OR using the related names

 def get_context_data(self, **kwargs):
        context = super(ClientDetails, self).get_context_data(**kwargs)
        context['servers'] = self.object.server_set.all()
        context['users'] = self.object.user_set.all()
        return context

You don't really need to do this in the view at all; you can follow the relationships in the template.

{{ object.name }}
{% for server in object.server_set.all %}
    {{ server.name }}
{% endfor %}
{% for user in object.user_set.all %}
    {{ user.first_name }}
{% endfor %}

Now you can remove your get_context_data method altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM