Django tastypie:如何检索子对象列表并将该列表附加到'choices'字段atrribute

时间:2015-01-26 16:50:03

标签: django django-models tastypie

我有一个名为Blueprint的模型类:

class Blueprint(models.Model):
    name = models.CharField(max_length=120)
    description = models.TextField()
    workloads = models.CharField(choices=WORKLOAD_CHOICES)

    class Meta:
        ordering = ["name", ]

此模型的子项名为工作负载。

对于django和tastypie都是全新的,我有这个问题:

1)我在哪里执行逻辑,它检索工作负载列表,并在models.py(作为 init 的一部分)或api.py中填充WORKLOAD_CHOICES: def obj_get的一部分?

P.S。这是api.py:

class BlueprintResource(ModelResource):
    def obj_create(self, bundle, request=None, **kwargs):
        return super(BlueprintResource, self).obj_create(bundle, request)

    def obj_update(self, bundle, request=None, **kwargs):

        blueprint = Blueprint.objects.get(id=kwargs.get("pk"))
        blueprint.description = bundle.data.get("description")
        blueprint.name = bundle.data.get("name")
        blueprint.workloads = bundle.data.get("workloads")
        blueprint.save()

        def obj_delete(self, bundle, **kwargs):

            return super(BlueprintResource, self).obj_delete(bundle)

    class Meta:
        queryset = Blueprint.objects.all()
        resource_name = 'blueprint'
        authorization=Authorization()

1 个答案:

答案 0 :(得分:1)

查看build_bundle()full_dehydrate()。我还没有对此进行测试,但也许这样的事情会起作用。

from my_app.models import WORKLOAD_CHOICES

class BlueprintResource(ModelResource):

    def full_dehydrate(self, bundle, for_list=False):

         dic = dict([WORKLOAD_CHOICES])
         bundle.data['foo'] = self.build_bundle(data=dic)

         return super(BlueprintResource, self).full_dehydrate(bundle, for_list)