[英]unable to access the Django autogenerated set accessor for my ambiguous foreign key
I have the following model: 我有以下模型:
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
I am expecting the autogeneration of an accessor which allows me to get the set of prerequisites of a resource, however neither of these works: 我期望自动生成访问器,这使我可以获得资源的先决条件集,但是这些都不起作用:
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'
The worst part of all this is that the admin interface works perfectly. 最糟糕的是,管理界面完美运行。 I am able to specify prereqs via pulldown and save them and they persist.
我能够通过下拉菜单指定先决条件并保存它们,并且它们会持续存在。 Here is my admin code:
这是我的管理员代码:
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)
You shouldn't add the _set
suffix for relations which have the related_name
attribute: 对于具有
related_name
属性的关系,不应添加_set
后缀:
r = Resource.objects.get(id=2)
r.prereq_resource.all()
r.prereq_backlink.all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.