下面是我的models.py
。问题是在管理面板User
中,模型中的列Ingredience
指向Ingredience Category
值而不是User
值。
在Ingredience
模型中我有2 个外键。我不确定这是否是问题所在。
管理面板截图:
模型.py:
from django.db import models
from django.contrib.auth.models import User
class IngredienceCategory(models.Model):
name = models.CharField(max_length=30)
user = models.ForeignKey(User, null=True, blank=True)
class Meta:
verbose_name_plural = "Ingredience Categories"
def __unicode__(self):
return self.name
class Ingredience(models.Model):
name = models.CharField(max_length=30)
category = models.ForeignKey(IngredienceCategory, null=True, blank=True)
user = models.ForeignKey(User, null=True, blank=True)
class Meta:
verbose_name_plural = "Ingredients"
def __unicode__(self):
return self.name
class Food(models.Model):
name = models.CharField(max_length=30)
ingredients = models.ManyToManyField(Ingredience)
html_id = models.CharField(max_length=30, null=True, blank=True)
user = models.ForeignKey(User, null=True, blank=True)
class Meta:
verbose_name_plural = "Foods"
def __unicode__(self):
return self.name
任何想法这里有什么问题?以下是我在出现此问题之前采取的步骤:
- 我
user
为所有 3 个模型添加了列并运行了南迁移 - 之后,我手动将值插入到所有 3 个表中的用户列
- 模型
IngredienceCategory
和Food
工作正常(即在User
下拉列表中显示用户列表 - 这是 SQL: http: //pastebin.com/3mHpXA3F
编辑: 要添加的东西(可能有助于解决此问题):我注意到单击管理面板中 Ingredience Model 中 User 列旁边的加号 (+),添加新用户的弹出表单是显示,这是正确的。
编辑 2: admin.py 文件的相关部分:
class IngredienceAdmin(admin.ModelAdmin):
search_fields = ('name',)
list_filter = ('category',)
ordering = ('name',)
# def formfield_for_foreignkey(self, db_field, request, **kwargs):
# #if db_field.name == 'ingrediencecategory':
# kwargs['queryset'] = IngredienceCategory.objects.order_by('name')
# return super(IngredienceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'ingrediencecategory':
kwargs['queryset'] = IngredienceCategory.objects.order_by('name')
return super(IngredienceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'user':
kwargs['queryset'] = User.objects.order_by('name')
return super(IngredienceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)