我想要的是能够根据 django Admin 中的 ForeignKey 选择器的选择来选择要显示的表单集。
我有四个模型:
- 产品
- 评分
- 标准(问题)
- 标准答案
我的数据库组织如下:
Product <- ManyToOne -- Rating <- ManyToMany -> Criterion -
| |
-- OneToMany -> CriterionAnswer <- OneToMany --
当我在管理员的产品模型表单中选择评级并保存产品时,我会创建与所选评级中的标准相对应的所有缺失的 CriterionAnswers。下次我打开产品时,我看到 CriterionAnswers 是内联的。如果我然后选择另一个评级,其他 CriterionAnswers 将被保存并与旧的一起显示。如何选择仅显示与所选评级相对应的 CriterionAnswers?
楷模:
################
# Product
################
class Product (models.Model):
rating = models.ForeignKey(
'Rating',
on_delete=models.SET_NULL,
null=True,
)
def save(self, *args, **kwargs):
super(Product, self).save(*args, **kwargs)
# get all criteria that need an answer in order to create the rating
criteriaToAnswer = Criterion.objects.filter(rating=self.rating)
# iterate over all criterias and check if the answer exists in database
for crit in criteriaToAnswer:
# if it doesn't exist, create an answer
if not CriterionAnswer.objects.filter(criterion=crit).filter(product=self):
print "Criteria answer to: <%s> does not exist... creating new one" % crit.__str__()
new_criterionAnswer = CriterionAnswer()
new_criterionAnswer.criterion = crit
new_criterionAnswer.product = self
new_criterionAnswer.save()
else:
print "Criteria answer to: <%s> exists." % crit.__str__()
################
# CriterionAnswer
################
class CriterionAnswer(models.Model):
criterion = models.ForeignKey('Criterion', on_delete=models.CASCADE)
product = models.ForeignKey('Product', on_delete=models.CASCADE)
################
# Rating
################
class Rating(models.Model):
name = models.CharField(max_length=30)
################
# Criterion
################
class Criterion(models.Model):
category = models.ForeignKey(
'Category',
on_delete=models.PROTECT,
)
rating = models.ManyToManyField(
'Rating',
through='CriterionInRating',
through_fields=('criterion', 'rating'),
)
行政:
class ProductAdmin(admin.ModelAdmin):
inlines = [
# Something here...
]
# Or something here that could solve my problem.