问题描述
我有一个Django模型中的一个属性,我想通过一个TastyPie模型资源公开。我的模型是
class UserProfile(models.Model)
_genderChoices =((uM,uMale),(uF,uFemale))
user = Models.OneToOneField(User,editable = False )
gender = models.CharField(max_length = 2,choices = _genderChoices)
def _get_full_name(self):
返回%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']
然而,我目前正在脱颖而出的口味api是:
{
gender:'female',
resource_uri:/ api / v1 / userprofile / 55 /
}
我已经尝试使用ModelResource中的fields属性,但这没有帮助。希望了解这里发生了什么。
您应该可以将其定义为尝试:
class UserProfileResource(ModelResource):
fullname = fields.CharField(attribute ='_ get_full_name',readonly = True)
class Meta:
queryset = models.UserProfile。 object.all()
authorization = DjangoAuthorization()
fields = ['gender',]
修改
您还必须包括: set readonly = True
您的 CharField
,或者TastyPie将尝试在插入或更新时设置其价值。
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.
You should be able to define it as a field try:
class UserProfileResource(ModelResource):
fullname = fields.CharField(attribute='_get_full_name', readonly=True)
class Meta:
queryset = models.UserProfile.objects.all()
authorization = DjangoAuthorization()
fields = ['gender',]
Edit
You also have to include: set readonly=True
on your CharField
, or TastyPie will try to set its value on insertion or update.
这篇关于如何在Django模型中显示属性(虚拟字段)作为TastyPie ModelResource中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!