【问题标题】:Access "server-side" model methods on TastyPie Resource访问 TastyPie 资源上的“服务器端”模型方法
【发布时间】:2013-02-08 15:03:37
【问题描述】:

我得到了这个资源,它工作正常并列出了员工的所有属性。

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

我有一个写在员工模型类上的方法,它列出了员工的电话号码(可怕的代码 imo。我认为它应该是一个属性,但我无法更改它)。

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

重点是编写一个 Resource 方法来访问该 Model 方法并使用 Employee 的属性列出结果..

【问题讨论】:

    标签: django django-models tastypie


    【解决方案1】:

    您应该能够在资源中将其创建为只读字段:

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

    如果您不设置readonly=True,Tastypie 将尝试在插入/更新时设置该字段的值。

    【讨论】:

      【解决方案2】:

      如果您的手机型号如下所示:

      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()
      

      还可以使用覆盖脱水方法自定义发送到客户端的数据。

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

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 2013-05-28
        • 2015-05-14
        • 2020-12-10
        • 2013-12-28
        • 2012-11-26
        • 1970-01-01
        • 1970-01-01
        • 2012-07-07
        相关资源
        最近更新 更多