我有以下型号:
class Program(models.Model):
name = models.CharField(max_length = 128)
def __unicode__(self):
return self.name
class Cheat(models.Model):
program = models.ForeignKey(Program)
shortcut = models.CharField(max_length = 64)
description = models.CharField(max_length = 512)
def __unicode__(self):
return u"(%s) - %s" % (self.shortcut, self.description)
class Category(models.Model):
#program = models.ForeignKey(Program)
name = models.CharField(max_length = 128)
def __unicode__(self):
return self.name
class Sheet(models.Model):
program = models.ForeignKey(Program)
name = models.CharField(max_length = 128)
def __unicode__(self):
return self.name
class CategorizedCheat(models.Model):
order = models.IntegerField(unique = True)
sheet = models.ForeignKey(Sheet)
cheat = models.ForeignKey(Cheat)
category = models.ForeignKey(Category)
def __unicode__(self):
return unicode(self.cheat)
在管理员中,我想显示一个带有CategorizedCheats内联的工作表。 问题是我不能只使用与工作表相同的程序作弊。有没有办法用Sheet.program过滤thoses?或者我的模型有问题吗?
答案 0 :(得分:1)
在Django管理员中过滤ForeignKeys中的可用对象时,正确的答案几乎总是ModelAdmin.formfield_for_foreignkey:
那里的文档解释了如何做到几乎完全正在寻找的东西。希望有所帮助!
答案 1 :(得分:0)
感谢Gabriel,这是最终的解决方案:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "cheat":
kwargs["queryset"] = Cheat.objects.filter(program=Sheet.objects.get().program)
return db_field.formfield(**kwargs)
return super(CategorizedCheatAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
诀窍是使用Sheet.objects.get()。程序,这是我缺乏的信息。