2012-11-14 90 views
2

我有tastypie和Django設置,他們工作得很好,我可以過濾,並通過HTTP修補對象。過濾反向關係

現在我想嘗試在反向關係上篩選我的結果,並且無法正常工作。

所以我的Django模型都像這樣,每個庫對象具有多重索引,每個多重指標可能有多個庫它使用:

class MultiplexIndex(models.Model): 
    multiplex_index_name = models.CharField(max_length = 100, unique=True) 
    multiplex_index_seq = models.CharField(max_length = 100, null=True, blank=True) 
    def __unicode__(self): 
     return "%s (%s)" % (self.multiplex_index_name , self.type.name) 
    class Meta: 
     ordering = ['multiplex_index_name'] 


class Library(models.Model): 
    sample = models.ForeignKey(Sample, db_index=True) 
    date_prepared = models.DateField(null=True, db_index=True) 
    multiplex_index = models.ForeignKey(MultiplexIndex , null=True , blank=True) 
    ... 
    ... 
    etc.... 

我Tastypie資源,像這樣(我曾嘗試各種組合):

class LibraryResource(ModelResource): 
    sample = fields.ToOneField('sequencing.api.SampleResource', 'sample') 
    multiplexindex = fields.ToOneField('sequencing.api.MultiplexIndexResource' , 'multiplex_index' , related_name='multiplexindex' , null=True) 
    loadedwith_set = fields.ToManyField('sequencing.api.LoadedWithResource' , 'loadedwith_set' , null=True) 
    class Meta: 
     queryset = Library.objects.all().order_by('-date_prepared') 
     resource_name = 'library' 
     paginator_class = Paginator 
     serializer = PrettyJSONSerializer() 
     filtering = { 
      'sample': ALL_WITH_RELATIONS , 
      'multiplexindex' : ALL_WITH_RELATIONS , 
      'loadedwith' : ALL_WITH_RELATIONS , 
      'id' : ALL , 
      'name': ALL 
     } 


class MultiplexIndexResource(ModelResource): 
    library = fields.ToManyField('sequencing.api.LibraryResource', attribute='library_set' , related_name='library') 
    class Meta: 
     queryset = MultiplexIndex.objects.all() 
     resource_name = 'multiplexindex' 
     serializer = PrettyJSONSerializer() 
     filtering = { 
      'multiplex_index_name' : ALL , 
      'library' : ALL_WITH_RELATIONS , 
     } 

我可以正確過濾「正向」。以下將返回具有多重索引92hp的所有庫。

http://127.0.0.1:8000/api/seq/library/?multiplexindex__multiplex_index_name=92hp&format=json 

但是,當我試圖對反向關係做一個過濾器時,我總是得到錯誤。我想在Django queryset API中做到這一點。

MultiplexIndex.objects.filter(library__name='515D') 

所以我的網址如下:

http://127.0.0.1:8000/api/seq/multiplexindex/?library__name=515D&format=json 

在這種情況下,我得到錯誤: 無法解析關鍵字「library_set」到現場。

(我想這個不斷變化的圖書館,但後來我得到的錯誤是: 「MultiplexIndex」對象有沒有屬性「庫」)

看來,我的MultiplexIndexResource的屬性=「library_set」是造成問題。當它被設置爲庫設置時,它將返回一個相關的管理器,但是過濾器將被設置爲「library_set__name = 515D」。當它被設置爲庫時,則MultiplexIndex表上沒有用於過濾的字段。

那麼有沒有一種簡單的方法來設置篩選,使其能夠反向工作?我錯過了什麼嗎?

回答

1

MultipleIndexResource上,不要將library_set視爲kwargs,而應視爲args。因此,更換attribute = 'library_set'library_set這樣的:

library = fields.ToManyField('sequencing.api.LibraryResource', 'library_set' , related_name='library') 

添加full = True如果你想。