0
我正在使用django 1.9。 我有以下Django模型:如何獲得Django模型中的所有相關對象ForeignKey和OneToOneField
@python_2_unicode_compatible
class Projects(models.Model):
index = models.IntegerField(blank=True,default=1)
year = models.CharField(max_length=255, blank=True)
title = models.CharField(max_length=255, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return '%s, %s, %s, %s' %(self.index,self.year,self.title,
self.description)
@python_2_unicode_compatible
class Awards(models.Model):
title = models.CharField(max_length=255, blank=True)
def __str__(self):
return '%s' %(self.title)
@python_2_unicode_compatible
class Images(models.Model):
projects = models.ForeignKey(Projects,null=True,blank=True, related_name='images_projects')
awards = models.OneToOneField(Awards,null=True,blank=True,related_name='images_awards')
title = models.CharField(max_length=255, blank=True)
file = models.ImageField(upload_to='upload_images/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s, %s' %(self.file, self.pk)
1)我試圖讓所有的模型對象項目和模型對象,會涉及到模型圖像項目Projects.objects.all().select_related('images_projects')
結果,我只得到模型對象項目。
2)我想獲取模型獎和圖像相關領域的所有對象。
Awards.objects.all().prefetch_related('images_awards')
因此,我只收到Award模型的所有字段。
如何在我的2個案例中將相關字段與主模型的所有對象一起獲取?
謝謝!你真的幫了! – voice