リレーションオブジェクトリファレンス

revision-up-to:11321 (1.1) unfinished

This document describes extra methods available on managers when used in a one-to-many or many-to-many related context. This happens in two cases:

  • The “other side” of a ForeignKey relation. That is:

    class Reporter(models.Model):
        ...
    
    class Article(models.Model):
        reporter = models.ForeignKey(Reporter)
    

    In the above example, the methods below will be available on the manager reporter.article_set.

  • Both sides of a ManyToManyField relation:

    class Topping(models.Model):
        ...
    
    class Pizza(models.Model):
        toppings = models.ManyToManyField(Topping)
    

    In this example, the methods below will be available both on topping.pizza_set and on pizza.toppings.

QuerySet.add(obj1[, obj2, ...])

指定したモデルオブジェクトを、披リレーションのセットに追加し (リレーショ ン先のオブジェクトからリレーションを張り)ます。

使い方:

>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.add(e) # Entry e を Blog b に関連づけます。
QuerySet.create(**kwargs)`

新たなオブジェクトを生成し、保存して、披リレーションのセットに追加しま す。新たに生成されたオブジェクトを返します:

>>> b = Blog.objects.get(id=1)
>>> e = b.entry_set.create(
...     headline='Hello',
...     body_text='Hi',
...     pub_date=datetime.date(2005, 1, 1)
... )

# e は自動的に保存されるので、 e.save() は呼ばなくてかまいません

上の例は、下記と同じ処理を実現します:

>>> b = Blog.objects.get(id=1)
>>> e = Entry(
....     blog=b,
....     headline='Hello',
....     body_text='Hi',
....     pub_date=datetime.date(2005, 1, 1)
.... )
>>> e.save()

リレーションを定義するためのキーワード引数を指定する必要はないので注意 してください。上の例では、 create()blog パラメタを渡してい ません。 Django は Entry オブジェクトの blog フィールドに自動的 に b をセットします。

QuerySet.remove(obj1[, obj2, ...])

指定したオブジェクトを披リレーションセットから除去します:

>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.

データベースの一貫性を保持するために、このメソッドは null=TrueForeignKey オブジェクトがリレーションを張っている先のモデルでしか使 えません。リレーションフィールドの値を None (NULL) にできなけれ ば、あるオブジェクトを披リレーションセットから除去したときに、何らかの 他のオブジェクトに対してリレーションを張り直さなければならないからです。 上の例で、 b.entry_set() からの e の除去は e.blog = None に 相当しますが、 blogForeignKey には null=True が設定され ていないので、これは無効な操作です。

QuerySet.clear()

披リレーションセットから、全てのオブジェクトを除去します:

>>> b = Blog.objects.get(id=1)
>>> b.entry_set.clear()

このメソッドは、リレーション元のオブジェクトを削除せず、ただ単にリレー ションを解除するだけなので注意してください。

remove() と同様、 clear()null=TrueForeignKey でしか使えません。