1

を持つモデルがあり、ManyToManyFieldそれを特定のプロパティを持つインスタンスに制限したい場合、これを行う最善の方法は何ですか? フォームバリデーションでもビューでもできますが、モデルに近いところでやりたいです。

たとえば、is_cool が True に設定されているクラス B のインスタンスのみをクラス A インスタンスに関連付けるにはどうすればよいでしょうか?

from django.db import models

class A(models.Model):
    cool_bees = models.models.ManyToManyField('B') 

class B(models.Model):
    is_cool = models.BooleanField(default=False)
4

1 に答える 1

3

モデルに近づけるために、m2m_changed 信号を使用して、モデルが要件に一致するかどうかを確認できます。コードは次のようになります。

import django.db.models.signals

def validate(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action == "pre_add":
        # if we're adding some A's that're not cool - a.cool_bees.add(b)
        if not reverse and model.objects.filter(pk__in=pk_set, is_cool=False):
              raise ValidationError("You're adding an B that is not cool")
        # or if we add using the reverse - b.A_set.add(a)
        if reverse and not instance.is_cool:
              raise ValidationError("You cannot insert this non-cool B to A")


signals.m2m_changed.connect(validate, sender=A.cool_bees.through)
于 2012-07-01T09:45:06.093 に答える