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個案例中將相關字段與主模型的所有對象一起獲取?

回答

2

select_relatedprefetch_related業績的助推器是檢索的當前查找相關的對象。查詢返回查找的相應對象(主要是),然後將相關對象一起提取;

您仍然需要使用常規語法來訪問Python中的相關對象。

例如

for p in Projects.objects.all().select_related('images_projects'): 
    print(p.images_projects) 

沒有數據庫的旅行將訪問p.images_projects,因爲它已經被取出沿着project進行。

+0

謝謝!你真的幫了! – voice

相關問題