这是我想要关联的模型。我希望收藏品以出现的形式出现。
class Collection(models.Model):
id = models.AutoField(primary_key=True, null=True)
code = models.CharField(max_length=100, null=True, blank=True)
address = models.CharField(max_length=100, null=True, blank=True)
collection_name = models.CharField(max_length=100)
def __unicode__(self):
return self.collection_name
class Meta:
db_table = u'collection'
ordering = ('collection_name',)
class Occurrence(models.Model):
id = models.AutoField(primary_key=True, null=True)
reference = models.IntegerField(null=True, blank=True, editable=False)
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
modified = models.DateTimeField(null=True, blank=True, auto_now=True)
class Meta:
db_table = u'occurrence'
每次我去检查Occurrence对象时都会收到此错误
TemplateSyntaxError at /admin/hotiapp/occurrence/
Caught an exception while rendering: column occurrence.collection_id does not exist
LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc..
每次我尝试添加新的事件对象时都会出现此错误
ProgrammingError at /admin/hotiapp/occurrence/add/
column occurrence.collection_id does not exist
LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll...
我做错了什么?或者ForeignKey如何运作?
答案 0 :(得分:1)
问题是您添加ForeignKey后没有更新数据库表定义。正如文档明确指出的那样,syncdb
不会为您执行此操作。您需要手动更新SQL,或使用像South这样的工具。
答案 1 :(得分:0)
你确定你的意思
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
可空和独特?在某些数据库中可能无法实现这一点。
通常,这里的唯一约束似乎没有多大意义。
您是否试图强制建立一对一的关系?使用OneToOneField。 http://docs.djangoproject.com/en/1.1/ref/models/fields/#django.db.models.OneToOneField