django-contentrelations 1.1 documentation
Using a resource requires instantiating the registered resource class with an instance of the appropriate class. In short:
ExampleResource(Example.objects.get(id=1))
But since you probably are missing key information about which resource goes with with object, there are some easier ways to do this.
If you have the model, you can get the resource class from the resource_list.
from contentrelations import resource_list
from simpleapp.models import Food
FoodResourceClass = resource_list[Food]
Then you can instantiate the class with any Food object.
food_item = Food.objects.get(id=1)
resource = FoodResourceClass(food_item)
An even simpler way to get a Resource is to use the ResourceList.get_for_instance() method on the resource_list object. This method takes an instance, and does the lookup and instantiation for you.
from contentrelations import resource_list
from simpleapp.models import Food
food_item = Food.objects.get(id=1)
resource = resource_list.get_for_instance(food_item)
A Resource class attempts to get an attribute several ways:
What if you have a list of items and you want to use them as Resources? That’s where the ResourceIterator comes in. the ResourceIterator wraps any iterator or sequence and returns each item’s registered Resource class. Here is a simple example:
>>> from articleapp.models import Article
>>> from imageapp.models import Image
>>> from downloads.models import DownloadableFile
>>> from contentrelations.resources import ResourceIterator
>>> a = Article.objects.all()[0]
>>> i = Image.objects.all()[0]
>>> d = DownloadableFile.objects.all()[0]
>>> items = [a, i, d]
>>> for i in ResourceIterator(items):
... print i
...
Article Resource
Image Resource
Downloadablefile Resource
When we passed a list of an Article, Image and Downloadable File to ResourceIterator we got back an iterator of their corresponding resources.