1

私はアイテムとレシピ(それが作成するアイテムにリンクされています)を持っています。レシピはthroughモデルを使用してレシピ内のアイテムの数を定義します。

今、私は次の問題を抱えています。数量に関係なく、アイテムを 1 回だけ持つようにレシピを制限したい。

したがって、アイテムがあり、 x1、x2 x2Breadを追加するとします。その後、誰かがそれらのアイテムのいずれかを再度追加しようとした場合にエラーを発生させたいと考えています。FlourButterSunseeds

どうすればそれができますか?

アップデート

unique_togetherとの解決策にrecipe_idなりitem_idますか?

更新 2 (一部のコード)

class Recipe_Has_Items(models.Model):

    recipe = models.ForeignKey('Recipe')
    item = models.ForeignKey('Item')
    quantity = models.IntegerField(validators = [MinValueValidator(0)])

    def __unicode__(self):
        return '%s (%d)' % (self.item, self.quantity)

    class Meta:
        verbose_name = 'Recipe\'s Item'
        verbose_name_plural = 'Recipe\'s Items'
4

1 に答える 1

1

私が理解しRecipeているように、ManyToManyFieldtoItemと through テーブルには、3 つのフィールドrecipe( ForeignKey)、item( ForeignKey)、およびが定義されていますitem_count。レシピの場合、アイテムは最大で 1 回使用できます (item_count >= 1 の場合)。したがって、はい、unique_togetherforrecipeitemin through table を追加するとうまくいきます。

于 2013-07-20T20:33:15.410 に答える