我将我的(PHP)旧站点的数据库表导入到Django中。默认情况下,它在模型中创建了一堆主键字段(因为其中大多数被称为诸如news_id
而不是id
)。更改Django的主键字段,现在项目不会出现在管理员
我刚刚将所有主键都重命名为id
,并从模型中删除了字段。然后问题就出现在我的新闻模型中。我添加的新东西不会出现在管理员中。当我删除从我的ModelAdmin以下行,它们显示出来:
list_display = ['headline_text', 'news_category', 'date_posted', 'is_sticky']
具体来说,它是news_category
场引起的问题。如果我从列表中删除它,那么我会看到我的新对象。现在,当我直接编辑这些项目(使用项目ID对网址进行黑客入侵)时,它们也具有有效的类别,同样在数据库中。以下是模型定义:
class NewsCategory(models.Model):
def __unicode__(self):
return self.cat_name
#news_category_id = models.IntegerField(primary_key=True, editable=False)
cat_name = models.CharField('Category name', max_length=75)
cat_link = models.SlugField('Category name URL slug', max_length=75, blank=True, help_text='Used in URLs, eg spb.com/news/this-is-the-url-slug/ - generated automatically by default')
class Meta:
db_table = u'news_categories'
ordering = ["cat_name"]
verbose_name_plural = "News categories"
class News(models.Model):
def __unicode__(self):
return self.headline_text
#news_id = models.IntegerField(primary_key=True, editable=False)
news_category = models.ForeignKey('NewsCategory')
writer = models.ForeignKey(Writer) # todo - automate
headline_text = models.CharField(max_length=75)
headline_link = models.SlugField('Headline URL slug', max_length=75, blank=True, help_text='Used in URLs, eg spb.com/news/this-is-the-url-slug/ - generated automatically by default')
body = models.TextField()
extra = models.TextField(blank=True)
date_posted = models.DateTimeField(auto_now_add=True)
is_sticky = models.BooleanField('Is this story featured on the homepage?', blank=True)
tags = TaggableManager(blank=True)
class Meta:
db_table = u'news'
verbose_name_plural = "News"
您可以看到我在哪里注释了自动生成的主键字段。
似乎Django认为我的新项目没有news_category_ids,但他们肯定会这样做。我尝试编辑现有的新闻并更改类别,并且正常工作。如果我运行搜索其中一个新项目,它不会显示,但搜索的底部显示“发现1个新闻”,所以发生了一些事情。
任何提示感激地收到。
编辑:这是我的ModelAdmin太:
class NewsCategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"cat_link": ("cat_name",)}
list_display = ['cat_name', '_cat_count']
def _cat_count(self, obj):
return obj.news_set.count()
_cat_count.short_description = "Number of news stories"
class NewsImageInline(admin.TabularInline):
model = NewsImage
extra = 1
class NewsAdmin(admin.ModelAdmin):
prepopulated_fields = {"headline_link": ("headline_text",)}
list_display = ['headline_text', 'news_category', 'date_posted', 'is_sticky'] #breaking line
list_filter = ['news_category', 'date_posted', 'is_sticky']
search_fields = ['headline_text']
inlines = [NewsImageInline]
您是否在更改模型后迁移数据库?尝试删除表格并再次运行syncdb – akonsu 2012-01-26 23:53:10
我运行了一个手动sql脚本来重命名列,具有相同的效果。 syncdb正常运行。 – 2012-01-27 00:02:15
是数据库中的主键还好吗?我的意思是你重命名字段发生了什么主键? – akonsu 2012-01-27 00:18:47