我有客户端,服务器,用户模型。在“客户详细信息视图”中,我想显示属于该公司的服务器和用户。我该如何过滤?
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
我该如何实现?
答案 0 :(得分:0)
如果您希望这是一般用例,即从服务器检索到的所有对象都必须用于特定客户端。您可以使用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
或使用相关名称
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
答案 1 :(得分:0)
您根本不需要在视图中执行此操作;您可以按照模板中的关系进行操作。
{{ object.name }}
{% for server in object.server_set.all %}
{{ server.name }}
{% endfor %}
{% for user in object.user_set.all %}
{{ user.first_name }}
{% endfor %}
现在,您可以完全删除get_context_data方法。