首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >跟随关系“向后”TastyPie

跟随关系“向后”TastyPie
EN

Stack Overflow用户
提问于 2018-04-05 05:43:10
回答 1查看 37关注 0票数 0

我正在尝试和TastyPie建立“反向”的关系,但是我并没有做到这一点。文档并没有涉及太多细节,我试着在网上搜索,但都无济于事。

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

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

代码语言:javascript
复制
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是这样的:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2018-04-10 23:50:37

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

代码语言:javascript
复制
paintings = fields.ToManyField(PaintingResource,
                               'paintings',
                               full=True)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49660915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档