Django admin:以编程方式选择内联中的可见字段集

时间:2016-09-29 11:38:48

标签: sql django django-forms django-admin formsets

我想要的是能够根据django Admin中ForeignKey选择器的选择来选择要显示的formset。

我有四种模式:

  1. 产品
  2. 评分
  3. 标准(问题)
  4. CriterionAnswer
  5. 我的数据库按如下方式组织:

    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.
    

0 个答案:

没有答案