如何在Django中使用泛型类视图过滤分类产品



我正在制作一个POS系统,其中有客户,每个客户都有自己的交易。我可以显示所有的交易,但很难弄清楚如何仅基于客户过滤交易。在models.py

class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
address = models.CharField(max_length=200)
number = models.IntegerField(null=True, blank=True)
class AccountHolder(models.Model):
customer = models.ForeignKey(Customer, on_delete=CASCADE)
date = models.DateTimeField(default=timezone.now, auto_created=True)
share_deposit = models.IntegerField(blank=True, null=True)
share_return = models.IntegerField(blank=True, null=True)
share_total = models.IntegerField(blank=True, null=True)

我想使用泛型类来进行过滤。内部views.py

class CustomerDetail(ListView):
model = AccountHolder
context_object_name = 'customers'
template_name = 'customertransaction.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['customers'] = context['customers'].filter(customer=self.request.customer)

如果您想要过滤基于泛型类的视图的结果, 重写get_queryset()方法而不是操纵context_data变量

def get_queryset(self):
customer_id = self.kwargs['id']  # Assume that the url is like /account_holder/5 where 5 is the id of the customer
customer = Customer.objects.get(id=customer_id)
return AccountHolder.objects.filter(customer=customer)

但是,如果由于某种原因,您被迫使用context_data,那么像这样纠正您的过滤器:

# You wrote customer=self.request.customer
# If you have not wrote any middleware, request have not attribut customer
# You must retrieve the customer and filter AccountHolder by it.
customer = Customer.objects.get(id=self.kwargs['id'])
context['customers'] = context['customers'].filter(customer=cutomer)

相关内容

  • 没有找到相关文章

最新更新