2012-04-13 74 views
3

鑑於以下API定義,我需要能夠按產品別名過濾事件。如何使用Tastypie通過相關模型屬性過濾API結果?

鑑於一個事件屬於一個工作,而一個工作屬於一個產品,我不確定如何規範。

api.py:

class ProductResource(ModelResource): 

    class Meta: 
     queryset = Product.objects.all() 
     resource_name = 'product' 
     allowed_methods = ['get'] 
     excludes = ['created_at','updated_at'] 
     filtering = { 
      'alias': ALL 
     } 

class EnvironmentResource(ModelResource): 

    class Meta: 
     queryset = Environment.objects.all() 
     resource_name = 'environment' 
     allowed_methods = ['get'] 
     excludes = ['created_at','updated_at'] 

class JobResource(ModelResource): 

    product = fields.ForeignKey(ProductResource, 'product') 

    class Meta: 
     queryset = Job.objects.all() 
     resource_name = 'job' 
     allowed_methods = ['get'] 
     excludes = ['created_at','updated_at'] 

class EventResource(ModelResource): 

    environment = fields.ForeignKey(EnvironmentResource, 'environment',full=True) 
    job = fields.ForeignKey(JobResource, 'job',full=True) 

    class Meta: 
     queryset = Event.objects.all() 
     resource_name = 'event' 
     allowed_methods = ['get'] 
     excludes = ['created_at','updated_at'] 
     filtering = { 
      HOW DO I FILTER BY PRODUCT ALIAS???? 
     } 

回答

11

鑑於以下過濾規格:

# In EventResource 
filtering = { 
    'job' : ALL_WITH_RELATIONS 
} 

# In JobResource 
filtering = { 
    'product' : ALL_WITH_RELATIONS 
} 

# In ProductResource 
filtering = { 
    'alias' : ALL 
} 

你應該能夠做到:

/api/events/job__product__alias=something 
+0

我怎麼看,應該工作,但我對在JobResource的產品過濾得到一個語法錯誤。 – 2012-04-16 14:49:24

+0

或許你可以與我們分享錯誤訊息? – kgr 2012-04-16 15:11:46

+0

'的SyntaxError在/ 無效的語法(api.py 34行) 請求方法:\t GET 請求URL:\t http://127.0.0.1:8000/ Django的版本:\t 1.3.1 異常類型:\t語法錯誤 異常值:\t 無效的語法(api.py,第34行)' – 2012-04-16 17:02:46

0

一個簡單的方法來實現這一目標是通過Advanced Filtering。這可以避免許多由ttypie ForeignKey字段生成的查詢。爲了安全起見,請記得在將數據添加到orm_filters之前手動驗證或清理過濾器輸入數據。

class EventResource(ModelResource): 

    class Meta: 
     queryset = Event.objects.all() 
     resource_name = 'event' 
     allowed_methods = ['get'] 

    def build_filters(self, filters=None): 

     if filters is None: 
      filters = {} 

     orm_filters = super(EventResource, self).build_filters(filters) 

     # Your filtering 
     if 'job__product__alias' in filters: 
      orm_filters['job__product__alias'] = filters.get(
       'job__product__alias') 

    return orm_filters 

他們,你應該能夠得到過濾後的結果做:

/api/events/?job__product__alias=something