Backbone-Relational and Django-Tastypie: many-to-many fields operating example
Asked Answered
S

0

6

May somebody provide an example of operating with many-to-many fields of django.db models' instances through django-tastypie and backbone-relational? That's possible now with using intermediate model.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=42)    

class Book(models.Model):
    authors = models.ManyToManyField(Author, related_name='books', through='Authorship')
    title = models.CharField(max_length=42)

class Authorship(models.Model):
    author = models.ForeignKey(Author)
    book = models.ForeignKey(Book)

Here are possible tastypie resources' configuration:

from tastypie import fields, resources

class AuthorResource(resources.NamespacedModelResource):
    books = fields.ToManyField('library.api.resources.AuthorshipResource', 'books')

    class Meta:
        resource_name = 'author'
        queryset = models.Author.objects.all()

class BookResource(resources.NamespacedModelResource):
    authors = fields.ToManyField('library.api.resources.AuthorshipResource', 'authors')

    class Meta:
        resource_name = 'book'
        queryset = models.Book.objects.all()

class AuthorshipResource(resources.NamespacedModelResource):
    author = fields.ToOneField('library.api.resources.AuthorResource', 'author')
    book = fields.ToOneField('.api.resources.BookResource', 'book')

    class Meta:
        resource_name = 'authorship'
        queryset = models.Authorship.objects.all()

How to save Author related with a few unsaved yet Books using one request to our server?

Stefansson answered 17/3, 2012 at 17:33 Comment(1)
Possible duplicate #22601723Madore

© 2022 - 2024 — McMap. All rights reserved.