我想要的是能够根据django Admin中ForeignKey选择器的选择来选择要显示的formset。
我有四种模式:
我的数据库按如下方式组织:
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.