Domanda

I'm using Django, Mezzanine, and Tastypie for a CMS I'm building. Tastypie exposes an API so that another app can consume data from the CMS. I have many Django models with ImageFields and I would like to perform some specific actions in Tastypie's ModelResource dehydrate method for all ImageFields, namely generate a few thumbnails. Rather than overriding dehydrate in every single model resource and targeting the ImageFields by name, I'd like to be able to automatically check if a resource's corresponding model has any ImageFields, and if so, add the thumbnails to the resource's bundle.

In summary, is there a way to iterate through a model resource's corresponding model's fields and check the type of each in the dehydrate method?

È stato utile?

Soluzione

You can access the model associated with the ModelResource using Meta.object_class. It's either defined explicitly, or infered from Meta.queryset. The meta class can be accessed from _meta attribute of the ModelResource instance.

The fields of a model can be access by fields attribute of the corresponding model's meta class (available under _meta attribute).

That said, the following should work:

class MyModelResource(ModelResource):
    class Meta:
        # If `object_class` is omitted, it's value is taken from
        # `queryset`, so defining both is optional.
        object_class = MyModel
        queryset = MyModel.objects.all()

    def dehydrate(self, bundle):
        # `model_class` == `MyModel`
        model_class = self._meta.object_class

        fields_list = model_class._meta.fields
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top