我有一个Django模型中的属性,我想通过TastyPie ModelResource公开。
我的模特是
class UserProfile(models.Model):
_genderChoices = ((u"M", u"Male"), (u"F", u"Female"))
user = Models.OneToOneField(User, editable=False)
gender = models.CharField(max_length=2, choices = _genderChoices)
def _get_full_name(self):
return "%s %s" % (self.user.first_name, self.user.last_name)
fullName = property(_get_full_name)
我的ModelResource是
class UserProfileResource(ModelResource):
class Meta:
queryset = models.UserProfile.objects.all()
authorization = DjangoAuthorization()
fields = ['gender', 'fullName']
然而,我现在摆脱tastypie api的是:
{
gender: 'female',
resource_uri: "/api/v1/userprofile/55/"
}
我尝试过使用ModelResource中的fields属性,但这没有帮助。很想知道这里发生了什么。
答案 0 :(得分:34)
您应该可以将其定义为field尝试:
class UserProfileResource(ModelResource):
fullname = fields.CharField(attribute='_get_full_name', readonly=True)
class Meta:
queryset = models.UserProfile.objects.all()
authorization = DjangoAuthorization()
fields = ['gender',]
修改强>
您还必须在set readonly=True
上添加CharField
,否则TastyPie会尝试在插入或更新时设置其值。
答案 1 :(得分:3)
脱水的完整示例:
class UserResource(ModelResource):
fullname = fields.CharField(readonly=True)
class Meta:
queryset = auth_models.User.objects.all()
resource_name = 'user'
def dehydrate_fullname(self, bundle):
return u"{first_name} {last_name}".format(
first_name=bundle.obj.first_name, last_name=bundle.obj.last_name)