【发布时间】: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