【发布时间】:2015-07-30 19:58:15
【问题描述】:
我有一个包含模型的设置,该模型具有一组外键对象,这些对象都继承自父类。围绕这个设计的所有代码都运行良好,但我目前正在集成 sweetpie 以进行 API 访问。
我似乎无法让 sweetpie 与有问题的模型之一很好地搭配。我已经设法让 GET 工作,但是所有尝试使 POST 进行创建或编辑工作要么导致 GET 中断,要么根本没有工作。我在下面列出了示例代码和当前的修复尝试。
简化模型:
class Container(models.Model):
variable = models.CharField(max_length=100)
class ParentClass(models.Model):
container = models.ForeignKey(Container)
order = models.IntegerField()
class FirstInheritor(ParentClass):
important_data = models.IntegerField(default=0)
class SecondInheritor(ParentClass):
other_data = models.IntegerField(default=0)
完整代码中有更多的实际继承者模型,但该示例具有相同的概念:来自父模型的多个继承者,该父模型具有我正在尝试启用的相关模型的外键(容器)的 api 可用性。
目前,我的美味派资源看起来像这样:
class FirstInheritorResource(resources.ModelResource):
container = fields.ForeignKey('api.ContainerResource', 'container')
class Meta:
queryset = FirstInheritor.objects.all()
authorization = Authorization()
allowed_methods = ['get', 'post']
class SecondInheritorResource(resources.ModelResource):
container = fields.ForeignKey('api.ContainerResource', 'container')
class Meta:
queryset = SecondInheritor.objects.all()
authorization = Authorization()
allowed_methods = ['get', 'post']
class ContainerResource(resources.ModelResource):
firsts = fields.ToManyField(FirstInheritorResource, attribute=lambda bundle: FirstInheritor.objects.filter(container=bundle.obj), related_name="parentclass", full=True, null=True)
seconds = fields.ToManyField(SecondInheritorResource, attribute=lambda bundle: SecondInheritor.objects.filter(container=bundle.obj), related_name="parentclass", full=True, null=True)
class Meta:
queryset = Container.objects.all()
authorization = Authorization()
allowed_methods = ['get', 'post']
使用此代码,GET 请求显然有效。我已经尝试将“firsts”和“seconds”的related_name 调整为几乎所有可能的东西(父类、容器、firstinheritor),并试图摆弄这两个 ToManyFields 的属性,但是因为没有 -direct- Container 和两个 Inheritor 模型之间的联系,他们找不到彼此。
我尝试将 toManyField 子类化并重写它的许多函数以查看更改事物或强制某些变量的效果,但我没有运气。
按照目前的配置,尝试使用第一或第二次发布数据会导致
{"error": "The 'container' field has no data and doesn't allow a default or null value."}
【问题讨论】:
标签: django django-models tastypie