2016-04-22 158 views
0

我想基于我的详细视图中的主键过滤对象。有没有一种方法可以在我的views.py中调用我的主键或者我可以按照其他方式进行过滤?这里是我的代码:Django DetailView:基于主键过滤对象

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 

回答

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 
+0

好了,所以我用:'PK = self.kwargs [ 'PK']'和工作。谢谢! –