2012-10-05 42 views
5

是否可以使用tastypie在相关模型中包含字段?Tastypie访问来自继承模型的字段

按我下面的模型:如果我坚持一个VideoContent和一个实例的TextContent到数据库,然后我就可以从我的内容资源2点的对象,但是,没有附加字段都可用。

是否可以包含来自相关模型的字段(在本例中为视频url和文本内容),并且可以满足未来添加更多内容类型的需求,而无需重写Content Resource,或者我来从这个错误的方向?

我们的目标是能够在不必修改的内容资源更CONTENTTYPES扩展(假设有可能把它摆在首位的工作)

Models.py:

class Content(models.Model): 
    parent = models.ForeignKey('Content', related_name='children', null=True, blank=True) 

class TextContent(Content): 
    text = models.CharField(max_length=100) 

class VideoContent(Content): 
    url = models.CharField(max_length=1000) 

然后我的资源:

class ContentResource(ModelResource): 
    children = fields.ToManyField('myapp.api.resources.ContentResource', 'children', null=True, full=True) 

    class Meta: 
     resource_name = 'content' 
     queryset = ContentResource.objects.all() 
     authorization = Authorization() 
     always_return_data = True 

回答

2

我发现了另一个答案一个很好的解决方案

Populating a tastypie resource for a multi-table inheritance Django model


我碰到了同样的问题 - 尽管我仍然在解决它的中间。目前为止我已经弄清了两件事:

django-model-utils提供了一个继承管理器,可以让您使用抽象基类来查询它的表,并且可以自动向下查询结果。

有一点要看看是提供给资源类dehydrate/rehydrate方法。

这是我做过什么:

class CommandResource(ModelResource): 

    class Meta: 
     queryset = Command.objects.select_subclasses().all() 

这只是让你一半 - 资源还必须包括脱水/水化的东西,因为你必须手动包对象了传输(或recieving )来自用户。

我现在意识到的事情是,这是超级哈希,并且必须有一个更好/更清洁的方式提供tastypie - 他们不能指望你必须做这种类型的手动重新包装在这些类型的情况 - 但是,也许他们会这样做。我只有8个小时的tastypie @这一点经验,所以如果我解释这一切都错了,也许一些不错的计算器用户可以设置我的直线。 :d:d:d

0

我有同样的要求,终于解决了这个问题。

我不喜欢在上面给出的链接,因为我不喜欢组合查询集和重新排序的想法的答案。

显然,您可以继承多个资源。

通过继承多个资源,包括资源的领域。
而且由于这些字段对每个资源都是唯一的,所以我在init中将它们设为空。

想知道是否有办法只列出父母一次。 (现在有两个,一个用于分类,一个用于分类)

class SudaThreadResource(ThreadResource): 

    def __init__(self, *args, **kwargs): 
     super(SudaThreadResource, self).__init__(*args, **kwargs) 

     for field_name, field_object in self.fields.items(): 
      # inherited_fields can be null                                                          
      if field_name in self.Meta.inherited_fields: 
       field_object.null=True 

    class Meta(ThreadResource.Meta): 
     resource_name = 'thread_suda' 
     usedgoodthread_fields = UsedgoodThreadResource.Meta.fields[:] 
     userdiscountinfothread_fields = UserDiscountinfoThreadResource.Meta.fields[:] 
     staffdiscountinfothread_fields = StaffDiscountinfoThreadResource.Meta.fields[:] 
     bitem_checklistthread_fields = BitemChecklistThreadResource.Meta.fields[:] 

     parent_field_set = set(ThreadResource.Meta.fields[:]) 

     field_set = set(
      set(usedgoodthread_fields) | 
      set(userdiscountinfothread_fields) | 
      set(staffdiscountinfothread_fields) | 
      set(bitem_checklistthread_fields) 
     ) 

     fields = list(field_set) 
     inherited_fields = list(field_set - parent_field_set) 


     queryset = forum_models.Thread.objects.not_deleted().exclude(
      thread_type__in=(forum_const.THREAD_TYPE_MOMSDIARY, forum_const.THREAD_TYPE_SOCIAL_DISCOUNTINFO) 
     ).select_subclasses()