我正在尝试根据详细视图中的主键过滤对象。有没有办法可以在我的views.py或其他方式调用我的主键,我可以相应地过滤?这是我的代码:
models.py
class Accounts(models.Model):
account_name = models.CharField(max_length=50)
pricing_id = models.ForeignKey('Pricing')
class OrderRecords(models.Model):
order_id = models.ForeignKey('Orders')
account_id = models.ForeignKey('Accounts')
item_id = models.ForeignKey('Items')
views.py
class AccountDetailView(generic.DetailView):
model = Accounts
template_name = "orders/accountdetail.html"
def get_context_data(self, **kwargs):
context = super(AccountDetailView, self).get_context_data(**kwargs)
context['orderrecords'] = OrderRecords.objects.filter(????????)
return context
更新
所以这就是我所做的改变:
views.py
class AccountDetailView(generic.DetailView):
model = Accounts
template_name = "orders/accountdetail.html"
def get_context_data(self, **kwargs):
pk = self.kwargs['pk']
context = super(AccountDetailView, self).get_context_data(**kwargs)
context['orderrecords'] = OrderRecords.objects.filter(account_id=pk)
return context
答案 0 :(得分:1)
是的,在您的观看中,只需致电:
def get_context_data(self, **kwargs):
pk = kwargs.get('pk') # this is the primary key from your URL
# your other code
context = super(AccountDetailView, self).get_context_data(**kwargs)
context['orderrecords'] = OrderRecords.objects.filter(????????)
return context