gpt4 book ai didi

python - 如何将 Django 模型上的属性(虚拟字段)公开为 TastyPie ModelResource 中的字段

转载 作者:IT老高 更新时间:2023-10-28 22:15:28 29 4
gpt4 key购买 nike

我想通过 TastyPie ModelResource 公开 Django 模型中的一个属性。

我的模特是

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']

但是,我目前从 sweetpie api 中得到的只是:

{
gender: 'female',
resource_uri: "/api/v1/userprofile/55/"
}

我尝试过使用 ModelResource 中的 fields 属性,但这并没有帮助。很想了解这里发生了什么。

最佳答案

您应该能够将其定义为 field试试:

class UserProfileResource(ModelResource):
fullname = fields.CharField(attribute='_get_full_name', readonly=True)
class Meta:
queryset = models.UserProfile.objects.all()
authorization = DjangoAuthorization()
fields = ['gender',]

编辑

您还必须在 CharField 上包含:set readonly=True,否则 TastyPie 将尝试在插入或更新时设置其值。

关于python - 如何将 Django 模型上的属性(虚拟字段)公开为 TastyPie ModelResource 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9078035/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com