2014-01-15 79 views
2

我有叫時呈現這樣的一些Tastypie資源:Django的Tastypie use_in有關係

{ 
    "meta":{ 
     "limit":1, 
     "next":"/api/v1/studio/?limit=1&offset=1", 
     "offset":0, 
     "previous":null, 
     "total_count":93 
    }, 
    "objects":[ 
     { 
     "full_address":"1234 Main St.", 
     "resource_uri":"/api/v1/studio/3/", 
     "state":{ 
      "resource_uri":"/api/v1/state/110/", 
      "state_id":110, 
      "state_name":"Colorado", 
      "studios":[ 
       "/api/v1/studio/3/", 
       "/api/v1/studio/4/", 
       "/api/v1/studio/5/", 
       "/api/v1/studio/6/", 
       "/api/v1/studio/8/", 
       "/api/v1/studio/11/", 
       "/api/v1/studio/12/", 
       "/api/v1/studio/13/", 
       "/api/v1/studio/14/", 
       "/api/v1/studio/15/", 
       "/api/v1/studio/1/", 
       "/api/v1/studio/2/" 
      ] 
     } 
     } 
    ] 
} 

我可以使用use_in與Tastypie排除從列表視圖相關領域?我可以排除類似如下的直接資源的字段:

exclude_this_field = fields.CharField(use_in='detail', attribute='exclude_this_field') 

State是Studio的ForeignKey字段。我如何排除相關資源?

studios = fields.Charfield(use_in='detail', attribute='state__state_id') 

我可以做這樣的工作來排除相關資源嗎?

+0

默認情況下不顯示相關字段。您需要將字段分隔到資源才能顯示它。你可以顯示你的資源狀態和工作室?那 –

+0

你是怎麼解決這個問題的? – marcelosalloum

回答

0

如果要隱藏ForeignKeyField的詳細信息或列表,請覆蓋資源的init Function並在調用對象父級init後添加use_in值。它應該看起來像這樣:

class YourResource(ModelResource) 
    ... 
    class Meta: 
     ... 
    def __init__(self, *args, **kwargs): 
     # Call the object's parent, which will set up and populate 
     # the Resource fields from the queryset provided 
     super(YourResource, self).__init__(*args, **kwargs) 
     # Now loop through the fields of the resource, and when we 
     # find the one we only want to be shown in the detail view, 
     # set its use_in attr appropriately 
     for field_name, field_object in self.fields.items(): 
      if field_name == 'yourForeignFieldName': 
       field_object.use_in = 'detail' 

我希望這可以幫助,歡呼!