简体   繁体   English

如何从TastyPie中的两个ForeignKey字段中获取数据?

[英]How can I get data from two ForeignKey fields in TastyPie?

I have two models. 我有两个模型。

class Eatery(models.Model):
    class Meta:
        db_table = 'eatery'

    date_pub = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=54, blank=True)
    description = models.TextField(max_length=1024)
    approve_status = models.BooleanField(default=False)
    author = models.ForeignKey(User, null=False, blank=True, default = None, related_name="Establishment author")

    class Comments(models.Model):
        class Meta:
            db_table = 'comments'

        eatery = models.ForeignKey(Eatery, null=False)
        author = models.ForeignKey(User, null=False)
        date_pub = models.DateTimeField(auto_now_add=True)
        approve_status = models.BooleanField(default=True)
        description = models.TextField(max_length=512)

My TastyPie models: 我的TastyPie模型:

class EateryCommentsResource(ModelResource):
    user = fields.ToOneField(UserResource, 'author', full=True)

    class Meta:
        queryset = Comments.objects.all()
        resource_name = 'comments_eatery'
        filtering = {
            'author': ALL_WITH_RELATIONS
        }
        include_resource_uri = False
        #always_return_data = True
        paginator_class = Paginator

class EateryResource(ModelResource):

    user = fields.ToOneField(UserResource, 'author', full=True)
    comments = fields.ForeignKey(EateryCommentsResource, 'comments', full=True)

    class Meta:
        queryset = Eatery.objects.all()
        #excludes = ['description']
        resource_name = 'eatery'
        filtering = {
            'author': ALL_WITH_RELATIONS,
            'comments': ALL_WITH_RELATIONS,
        }
        fields = ['user', 'comments']
        allowed_methods = ['get']
        serializer = Serializer(formats=['json'])
        include_resource_uri = False
        always_return_data = True
        paginator_class = Paginator
        authorization = DjangoAuthorization()

I can't getting EateryResource with comments. 我无法获得带有评论的EateryResource。 When I getting without comments, It works. 当我没有评论时,它起作用。 How can I get EateryResourse with UserResource and CommentsResource. 如何通过UserResource和CommentsResource获得EateryResourse。 Sorry for my English. 对不起我的英语不好。 Thanks. 谢谢。

Since the comments are linked to your eatery throug a ForeignKey, you need to define your EateryResource like this: 由于注释是通过ForeignKey链接到您的餐馆的,因此您需要这样定义EateryResource

class EateryResource(ModelResource):

    user = fields.ToOneField(UserResource, 'author', full=True)
    comments = fields.ToManyField(EateryCommentsResource, 'comment_set', full=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM