2015-03-13 45 views
0

我有以下型號:無法訪問Django的自動生成set訪問我的曖昧外鍵

from django.db import models 
from django.utils import timezone 

class Resource(models.Model): 
    title = models.CharField(max_length=300) 
    shortcode = models.CharField(max_length=20, null=True, blank=True) 
    img = models.URLField(null=True, blank=True) 
    summary = models.TextField(null=True, blank=True) 
    url = models.URLField('Link to Resource', null=True, blank=True) 
    pub_date = models.DateTimeField('date published') 

    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 

    def __unicode__(self): 
     return self.title 

class Prereq(models.Model): 
    prereq = models.ForeignKey(Resource, null=True, related_name='prereq_backlink') 
    resource = models.ForeignKey(Resource, null=True, related_name='prereq_resource') 

    def __unicode__(self): 
     return self.prereq.title 

class Concurrent(models.Model): 
    concurrent = models.ForeignKey(Resource, null=True, related_name='concurrent_backlink') 
    resource = models.ForeignKey(Resource, null=True, related_name='concurrent_resource') 

    def __unicode__(self): 
     return self.concurrent.title 

class Concomitant(models.Model): 
    concomitant = models.ForeignKey(Resource, null=True, related_name='concomitant_backlink') 
    resource = models.ForeignKey(Resource, null=True, related_name='concomitant_resource') 

    def __unicode__(self): 
     return self.concomitant.title 

我期待的訪問,讓我得到了一組資源的先決條件的自動生成,但是這些工作都沒有:

r = Resource.objects.get(id=2) 
r.prereq_resource_set # AttributeError: 'Resource' object has no attribute 'prereq_resource_set' 

r.prereq_backlink_set # AttributeError: 'Resource' object has no attribute 'prereq_resource_set' 

所有這一切中最糟糕的部分是管理界面完美工作。我可以通過下拉菜單指定prereq並保存它們,並且它們會一直存在。這裏是我的管理代碼:

from django.contrib import admin 
from idhhb.models import Resource, Prereq, Concurrent, Concomitant 

class PrereqInline(admin.TabularInline): 
    model = Prereq 
    fk_name = 'prereq' 
    extra = 5 

class ConcurrentInline(admin.TabularInline): 
    model = Concurrent 
    fk_name = 'concurrent' 
    extra = 3 

class ConcomitantInline(admin.TabularInline): 
    model = Concomitant 
    fk_name = 'concomitant' 
    extra = 3 

class ResourceAdmin(admin.ModelAdmin): 
    fieldsets = [ 
     (None, {'fields': 'title shortcode img summary url pub_date'.split() }), 
    ] 
    inlines = [PrereqInline,] 


admin.site.register(Resource, ResourceAdmin) 

回答

2

你不應該添加_set後綴,因爲他們related_name屬性關係:

r = Resource.objects.get(id=2) 
r.prereq_resource.all() 
r.prereq_backlink.all()