【问题标题】:Following relationships “backward” TastyPie追随关系“落后”的美味派
【发布时间】:2018-09-14 14:24:34
【问题描述】:

我正试图追随与 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()

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2023-03-10
      • 2012-10-30
      • 2014-01-23
      • 1970-01-01
      • 2012-04-18
      • 2019-07-03
      相关资源
      最近更新 更多