1

私が欲しいのは、django Admin の ForeignKey セレクターの選択に従って、表示するフォームセットを選択できるようにすることです。

私は4つのモデルを持っています:

  1. 製品
  2. 評価
  3. 基準(質問)
  4. CriterionAnswer

私のデータベースは次のように構成されています。

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.
4

0 に答える 0