我正在尝试和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()发布于 2018-04-10 23:50:37
ToManyField的第一个参数是相关模型to。所以用PaintingResource替换self。此外,连接将自动过滤相关对象,因此lambda是不必要的。
paintings = fields.ToManyField(PaintingResource,
'paintings',
full=True)https://stackoverflow.com/questions/49660915
复制相似问题