适用于多种型号的Tastypie api

时间:2016-02-23 04:28:43

标签: django tastypie

我有两个型号

class LCUser(models.Model):
    email = models.CharField(max_length=100,unique=True)
    password = models.CharField(max_length=100)

class UserProfile(models.Model):
    user = models.OneToOneField(LCUser,primary_key=True)
    mobile_phone = models.IntegerField(null=True)
    address = models.CharField(max_length=500,null=True)

class UserProfileResource(MultipartResource, ModelResource): 
    class Meta:
        resource_name = 'profile'
        queryset = UserProfile.objects.all()

我想设置/ profile / endpoint,以便CRUD操作管理所有5个字段。

1)我可以这样做吗? 2)这是一个好习惯吗? 3)如果不是我的替代品?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

class LCUser(models.Model):
    email = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=100)

class UserProfile(models.Model):
    user = models.OneToOneField(LCUser, primary_key=True)
    mobile_phone = models.IntegerField(null=True)
    address = models.CharField(max_length=500, null=True)

class LCUserResource(MultipartResource, ModelResource):
    class Meta:
        resource_name = 'lcuser'
        queryset = LCUser.objects.all()
        excludes = ('password',)

class UserProfileResource(MultipartResource, ModelResource):
    user = fields.ToOneField(LCUserResource, 'user')

    class Meta:
        resource_name = 'profile'
        queryset = UserProfile.objects.all()

确保排除密码,您不希望被读取。