我已尝试过其他问题,但我仍然遇到一些问题。
我有2个型号:
class Media(models.Model):
name = models.CharField(max_length=100)
media = models.CharField(max_length=10, choices=MEDIA_TYPE)
class Review(models.Model):
message = models.CharField(max_length=10)
submitter = models.ForeignKey(User)
media = models.ForeignKey(Media, related_name='rev_media')
我想去做像
这样的事情blaw = Media.objects.all()
for a in blaw:
print (all the reviews to have to do with this one media object)
答案 0 :(得分:0)
rev_media
,您的related_name,应该为您提供将其作为外键的所有评论:
blaw = Media.objects.all()
for a in blaw:
print media.rev_media.all()
答案 1 :(得分:0)
由于您有related_name
,因此可以使用a.rev_media.all()
获取关联对象列表。
现在,你可以这样做:
media_qs = Media.objects.all()
for media in media_qs:
reviews = media.rev_media.all() #basically, this is the queryset of all the associated reviews for this media object.
if reviews.exists():
print ", ".join([review.message for review in reviews])