Tastypie ToOneField无法正常工作

时间:2017-02-19 07:59:59

标签: django tastypie

我的模特:

class UserDetails(models.Model):
    user=models.ForeignKey(User)
    email=models.CharField(max_length=30)
    name=models.CharField(max_length=30)

class Problem(models.Model):
    user=models.OneToOneField(UserDetails)
    onset_time=models.CharField(max_length=20)
    symptoms=models.CharField(max_length=50)

资源:

class ProblemResource(ModelResource):
    class Meta:
        queryset=Problem.objects.all()
        resource_name="hypo"

class UserResource(ModelResource):
    hypo=fields.ToOneField(ProblemResource,'hypo')
    class Meta:
        queryset=UserDetails.objects.all()
        resource_name="user"

我想使用'/ user'api调用来获取特定用户的问题,但我收到此错误: -

{“error”:“模型'< UserDetails:UserDetails对象>'有一个空属性'hypo'并且不允许空值。“}

我已经浏览了数据并且没有空值。

3 个答案:

答案 0 :(得分:0)

如果在模型中指定null的默认值,该怎么办?

user=models.OneToOneField(UserDetails, on_delete=models.SET_NULL, null=True, blank=True)

答案 1 :(得分:0)

这里的问题是UserResource中的属性'hypo'。 根据docs属性意味着:

  

一个字符串,命名由Resource包装的对象的实例属性。该属性将在脱水过程中被访问或在水合物期间被写入。

所以在你的情况下,在UserResource中,'hypo'不是属性,'problem'是正确的属性(引用你的模型)。

因此,更改UserResource中的属性可以解决问题:

class UserResource(ModelResource):
    hypo=fields.ToOneField(ProblemResource,'problem')
    class Meta:
        queryset=UserDetails.objects.all()
        resource_name="user"

了解详情:http://django-tastypie.readthedocs.io/en/latest/fields.html#common-field-options

答案 2 :(得分:0)

我能够通过在问题模型

中提供related_name='hypo'来解决问题
class Problem(models.Model):
   user=models.OneToOneField(UserDetails,related_name='hypo')
   onset_time=models.CharField(max_length=20)
   symptoms=models.CharField(max_length=50)

Django documentation包含有关related_name标记的更多详细信息。

相关问题