我对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请求中准备数据,以便填充Profile
和User
?此外,与ForeignKey
或ManyToMany
关系相关的模型如何?