0

In django, I have two models - User and UserProfile. There may exist zero or one profiles for a particular user. I'm trying to include the information from the UserProfile model directly on the UserResource.

I would like to use the profile ToManyField, if it exists, to access the contents of the associated UserProfile model. I've tried a variety of things in dehydrate, including self.profile.get_related_resource(self) and UserProfile.objects.get(id=...), but I can't seem to find my way from the profile field to the model object. Can anybody help me out?

I'm still new to Python, Django, and Tastypie, so hopefully if I'm doing anything awful somebody will be kind enough to point it out.

The goal is to have JSON that looks like this: { resourceUri: /v1/users/1 date_of_birth: Jan 1, 1980 ... etc }

where date_of_birth is a property of the UserProfileResource. I don't want all of the fields from UserProfileResource, and I don't want the UserProfile to be a nested object in the response - I want some fields from UserProfileResource to be top-level fields in the response, so that they look like part of the User resource.

class UserResource(ModelResource):
    profile = fields.ToOneField('foo.api.UserProfileResource', 'user', null=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'
        allowed_methods = ['get']
        #etc...


class UserProfileResource(ModelResource):
    date_of_birth = ...
    #etc
4

1 回答 1

1

我假设您使用的是 Django 1.4 和AUTH_PROFILE_MODULE?

由于 User:UserProfile 关系是 1:1,我会选择ToOneField。这将序列化为指向您的 UserProfileResource 的 URI 指针(如果存在)。如果您希望 UserProfileResource 字段数据与您的 UserResource 内联,您可以full=True在 ToOneField 定义中指定。使用这种方法,您不需要覆盖脱水。

此外,确保 ToOneField 定义中的第二个参数是指向您的 UserProfile Django 模型的 User 属性。例如,如果你OneToOneField(User, related_name='profile')的 Django 模型中有,那么这个属性应该是profile.

class UserResource(ModelResource):
    profile = fields.ToOneField('foo.api.UserProfileResource', 'profile', 
                                full=True, null=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'
        allowed_methods = ['get']

如果您所追求的是来自 UserProfile 实例的特定字段与您的用户混合,您应该能够执行以下操作:

class UserResource(ModelResource):
    date_of_birth = fields.DateField('profile__date_of_birth', null=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'
        allowed_methods = ['get']
        fields = ['userfields', 'gohere', 'date_of_birth']
于 2013-08-08T13:59:46.507 回答