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

Django tastypie: how to retrieve a list of child objects and attach that list to the 'choices' field atrribute

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

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) 我在哪里执行逻辑,它检索工作负载列表,并填充 WORKLOAD_CHOICES: 在 models.py 中(作为 init[= 的一部分24=]) 或在 api.py 中作为 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()

看看build_bundle() and 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)