2013-02-08 69 views
0

我得到了这个资源,它工作正常,列出了员工的所有属性。在TastyPie资源上访问“服务器端”模型方法

class EmployeeResource(ModelResource): 
    journey = fields.ForeignKey(WorkJourney, 'work_journey') 
    class Meta: 
     queryset = Employee.objects.all() 
     resource_name = 'employee' 
     authentication = BasicAuthentication() 

我writen对员工的模型类的方法,从一个员工列出了电话号码的(可怕的伊莫代码,我认为它应该是一个属性,但我不能改变它)。

@property 
def phones(self): 
    return u'/'.join([self.personal_phones or u'', self.institutional_phones or u'']) 

关键是要编写访问模型方法,并列出结果与员工的属性的资源方法..

回答

1

您应该能够将其创建为您的资源只读域:

phones = fields.CharField(attribute='phones', readonly=True) 

如果您未设置readonly=True,Tastypie会尝试设置插入/更新时的字段值。

0

如果您的手机型号是这样的:

class Phone(models.Model) 
    employee = models.ForeignKey(Employee, related_name=phones) 

然后你就可以得到所有的手机都为员工的名单在你EmployeeResource ToManyRelation用手机定义:

class EmployeeResource(ModelResource): 
    phones = fields.ToManyField(PhoneResource, 'phones', full=True) 
class Meta: 
    queryset = Employee.objects.all() 
    resource_name = 'employee' 
    authentication = BasicAuthentication() 

还与覆盖脱水方法可以自定义数据将发送给客户端的内容。

自定义视图是发送自定义数据的另一种解决方案。

相关问题