如何将 Django 模型上的属性(虚拟字段)公开为 TastyPie ModelResource 中的字段
我在 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 属性,但这没有帮助。很想了解这里发生了什么。
I have a property in a Django Model that I'd like to expose via a TastyPie ModelResource.
My Model is
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)
My ModelResource is
class UserProfileResource(ModelResource):
class Meta:
queryset = models.UserProfile.objects.all()
authorization = DjangoAuthorization()
fields = ['gender', 'fullName']
However all I'm currently getting out of the tastypie api is:
{
gender: 'female',
resource_uri: "/api/v1/userprofile/55/"
}
I have tried playing with the fields property in the ModelResource, but that hasn't helped. Would love to understand what is going on here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够将其定义为 字段 尝试:
编辑
您还必须在
CharField
上添加:set readonly=True
,否则 TastyPie 将尝试在插入或更新时设置其值。You should be able to define it as a field try:
Edit
You also have to include:
set readonly=True
on yourCharField
, or TastyPie will try to set its value on insertion or update.脱水的完整示例:
A full example with dehydrate: