Search code examples
pythondjangotastypie

Dynamic Models in tastypie


I have a class which returns json

[{      
            'title': 'Test Blog Title 1',
            'content': 'Blog Content',
            'author_name': 'User 1'
 },
 {
            'title': 'Test Blog Title 2',
            'content': 'Blog Content 2',
            'author_name': 'User 2'
 }]

I want to create Tastypie Model Resource based on the returned Json

I tried the Below Url this worked but i dont want to declare fields it should be dynamic

http://thehungrycoder.com/python/using-non-orm-data-sources-with-tastypie-in-django.html

class BlogResource(Resource):
    #i dont want the fields below instead want it to be dynamic based on json
    title = fields.CharField(attribute='title')
    content = fields.CharField(attribute='content')
    author = fields.CharField(attribute='author_name')

    class Meta:
        resource_name = 'blogs'

Solution

  • If you' don't declare fields, they won't be accessible in the bundle. However, they'll always be accessible in the request.

    You'll need to have at least one predefined field, to be used as a primary key. While you don't explicitly need to create it, you should have a way of knowing what object to return if the user issues a GET request for some object.