以下关系“落后”TastyPie

时间:2018-04-04 21:43:10

标签: django python-3.x django-models tastypie

我试图跟随TastyPie“向后”关系,但我还没有完全成功。文档并没有真正详细说明,我尝试在网上搜索无济于事。

我知道在Django中我可以实现它like this,但我如何在TastyPie中实现相同的目标呢?

我的models.py看起来像这样:

from django.db import models
from django.contrib.auth.models import User

class Gallery(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    created = models.DateField()

    def __str__(self):
        return '%s %s' % (self.name, self.created)

class Painting(models.Model):
    name = models.CharField(max_length=50)
    url = models.CharField(max_length=250)
    description = models.CharField(max_length=800)
    gallery = models.ForeignKey(Gallery, on_delete=models.PROTECT)
    published = models.DateField()

    def __str__(self):
        return '%s %s' % (self.name, self.published)

class Comment(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    painting = models.ForeignKey(Painting, on_delete=models.CASCADE)
    content = models.CharField(max_length=500)
    published = models.DateField()

    def __str__(self):
        return '%s %s' % (self.content, self.published)

我的resources.py看起来像这样:

from tastypie.resources import ModelResource
from api.models import Gallery, Painting, Comment
from tastypie.authorization import Authorization
from tastypie import fields
from django.contrib.auth.models import User

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'

class GalleryResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')

    #This does not work.
    paintings = fields.ToManyField(
        'self',
        lambda
        bundle: bundle.obj.painting_set.all(),
        full=True)

    class Meta:
        queryset = Gallery.objects.all()
        resource_name = 'gallery'
        authorization = Authorization()

class PaintingResource(ModelResource):
    gallery = fields.ForeignKey(GalleryResource, 'gallery')

    class Meta:
        queryset = Painting.objects.all()
        resource_name = 'painting'
        authorization = Authorization()

class CommentResource(ModelResource):
    painting_id = fields.ForeignKey(PaintingResource, 'painting')

    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comment'
        authorization = Authorization()

1 个答案:

答案 0 :(得分:0)

ToManyField的第一个参数是to,即相关模型。因此,将self替换为PaintingResource。此外,连接将自动过滤相关对象,因此不需要lambda。

paintings = fields.ToManyField(PaintingResource,
                               'paintings',
                               full=True)