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。 對不起,我的英文。謝謝。
但是我這樣定義的: 評論= fields.ForeignKey(EateryCommentsResource,「評論」,全=真) – Vitek
是在你的資源,這是錯誤的。因爲在你的模型中,它被定義爲一個餐館可以有很多評論(因爲評論有一個ForeignKey餐館)。如果你在簡單的django範圍內,你會通過'eatery.comment_set.all()'(返回一個評論列表)來獲得你對食堂的所有評論。所以你需要在你的資源上反映這一點 - 好吧... –
它的工作。感謝您的解釋! – Vitek