在django-tastypie中使用相关资源的POST请求

时间:2013-02-01 10:07:56

标签: django tastypie

我对django-tastypie和django一般都是新手。我使用tastypie保存相关资源时遇到了一些问题。我有一个包含其他字段的个人资料,并与用户模型OneToOneField相关联。我的客户端表单将提交所有必要的数据,以便为POST创建新用户UserResource

models.py

class Profile(models.Model):
    USER_TYPE_CHOICES = (
        ('A', 'Agent'),
        ('U', 'User'),
    )
    user = models.OneToOneField(User)
    type = models.CharField(max_length=1, choices=USER_TYPE_CHOICES, default='U')
    middle_name = models.CharField(blank=True, default='', max_length=100)
    created_on = models.DateTimeField(default=datetime.now())
    updated_on = models.DateTimeField(editable=False, auto_now=True, auto_now_add=True)

    def __unicode__(self):
        return '%s' % (self.username)

    def __save__(self, *args, **kwargs):
        self.updated_on = datetime.now()
        super(Profile, self).save()


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = Profile.objects.get_or_create(user=instance)

models.signals.post_save.connect(create_user_profile, sender=User)

api.py

class ProfileResource(ModelResource):
    class Meta:
        queryset = Profile.objects.all()
        resource_name = 'profile'
        excludes = ['updated_on', 'created_on']
        filtering = {
            'email': ALL,
            'type': ALL,
        }


class UserResource(ModelResource):
    profile = fields.ToOneField(ProfileResource, 'profile', full=True)
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['password', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login']
        filtering = {
            'username': ALL,
            'email': ALL,
        }

如何在POST请求中准备数据,以便填充ProfileUser?此外,与ForeignKeyManyToMany关系相关的模型如何?

0 个答案:

没有答案