2013-04-15 4 views
8

Làm thế nào để làm một bộ lọc trên Mô hình Django bằng cách sử dụng một đối số từ điển chứ không phải là phương thức? Đây là những gì tôi có quyền ở đây:Mô hình Bộ lọc Django theo từ điển

class StoreView(TemplateView): 

    def get(self, request): 

     # A bunch of gets 
     sort = request.GET.get('sort') 
     sort_price = request.GET.get('sort_price') 
     sort_mfr_method = request.GET.get('mfr_method') 

     # The params tpsort by 
     sort_params = {} 

     if sort is not None: 
      sort_params['sort'] = sort 

     if sort_price is not None: 
      sort_params['sort_price'] = sort_price 

     if sort_mfr_method is not None: 
      sort_params['sort_mfr_method'] = sort_mfr_method 

     # The Model Query 
     design_list = models.Design.objects.filter(sort_params) 

     # etc... 

Side Câu hỏi, là có một cách tốt hơn thiết lập các giá trị điển so với những gì tôi đang làm trên? Chẳng hạn như một thứ ba, nhưng theo một cách mà sẽ làm cho giá trị không tồn tại nếu nó không có?

sort_params['sort'] = sort if not None else '' 
+0

http://stackoverflow.com/questions/15949816/ use-string-variable-kwargs-as-named-argument –

Trả lời

15

Bạn sử dụng một từ điển để vượt qua đối số từ khóa như thế này:

models.Design.objects.filter(**sort_params) 

 

Không có built-in cách để có điều kiện thiết lập một phím dict, nhưng nếu bạn làm một này rất nhiều, bạn có thể viết của riêng bạn:

def set_if_not_none(mapping, key, value): 
    if value is not None: 
     mapping[key] = value 

class StoreView(TemplateView): 

    def get(self, request): 

     # A bunch of gets 
     sort = request.GET.get('sort') 
     sort_price = request.GET.get('sort_price') 
     sort_mfr_method = request.GET.get('mfr_method') 

     # The params tpsort by 
     sort_params = {} 

     set_if_not_none(sort_params, 'sort', sort) 
     set_if_not_none(sort_params, 'sort_price', sort_price) 
     set_if_not_none(sort_params, 'sort_mfr_method', sort_mfr_method) 

     # The Model Query 
     design_list = models.Design.objects.filter(**sort_params) 
+0

Điều đó làm việc tuyệt vời! Điều đó có ý nghĩa bởi vì .filter có thể được định nghĩa gần: 'filter (* args, ** kwargs)' Tôi chưa bao giờ nhận ra rằng bạn có thể làm được điều đó thật tuyệt vời! Cảm ơn – JREAM

4

the abo đã trả lời là đúng và tôi đề nghị một số hiệu quả hơn.

đây request.GET là QueryDict Chỉ cần chuyển đổi nó thành một từ điển như

kwargs = dict(request.GET)

này và bây giờ lọc nó

models.Design.objects.filter(**kwargs)