2016-01-20 78 views
1

我有两种模式。如何从TastyPie中的两个ForeignKey字段获取数据?

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) 

我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() 

我不能评论越来越EateryResource。当我没有评论,它的工作。如何通过UserResource和CommentsResource获得EateryResourse。 对不起,我的英文。谢谢。

回答

2

由于评论链接到你的餐馆通过量一个ForeignKey,你需要定义EateryResource这样的:

class EateryResource(ModelResource): 

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

但是我这样定义的: 评论= fields.ForeignKey(EateryCommentsResource,“评论”,全=真) – Vitek

+1

是在你的资源,这是错误的。因为在你的模型中,它被定义为一个餐馆可以有很多评论(因为评论有一个ForeignKey餐馆)。如果你在简单的django范围内,你会通过'eatery.comment_set.all()'(返回一个评论列表)来获得你对食堂的所有评论。所以你需要在你的资源上反映这一点 - 好吧... –

+0

它的工作。感谢您的解释! – Vitek

相关问题