Shinya Okano avatar Shinya Okano committed e05d52f

refs #20 ドキュメントにDjangoのモデルオブジェクトでListDelegateFieldを使う場合の注意点を追記

Comments (0)

Files changed (1)

docs/ja/source/usage.rst

 .. code-block:: pycon
 
    >>> from django.db import models
-   >>> from bpmappers.djangomodel import *
+   >>> from bpmappers.djangomodel import ModelMapper
    >>> class Person(models.Model):
    ...    name = models.CharField(max_length=10)
    ...    val = models.IntegerField()
 ``bpmappers.ListDelegateField`` には、引数としてMapperを継承したクラスを指定します。
 この例では、 ``TeamMapper.members`` の値はリストとして展開されて、 ``PersonMapper`` を使ってマッピングを行うように定義されています。
 
+DjangoのManyToManyFieldをマッピングする場合、ListDelegateFieldにはDjangoのManagerオブジェクトが渡されるため、filterパラメータを指定する必要があります。
+
+.. code-block:: pycon
+
+   >>> from django.db import models
+   >>> from bpmappers import Mapper, RawField, ListDelegateField
+   >>> class Person(models.Model):
+   ...     name = models.CharField(max_length=10)
+   ...
+   >>> class Group(models.Model):
+   ...     name = models.CharField(max_length=10)
+   ...     persons = models.ManyToManyField(Person)
+   ...
+   >>> class PersonMapper(Mapper):
+   ...     name = RawField()
+   ...
+   >>> class GroupMapper(Mapper):
+   ...     name = RawField()
+   ...     # filterを指定する
+   ...     persons = ListDelegateField(PersonMapper, filter=lambda manager: manager.all())
+   ...
+   >>> person1 = Person.objects.create('wozozo', 123)
+   >>> person2 = Person.objects.create('feiz', 456))
+   >>> group = Group.objects.create('test')
+   >>> group.persons.add(person1)
+   >>> group.persons.add(person2)
+   >>> mapper = GroupMapper(group)
+   >>> print mapper.as_dict()
+   {'name': 'test', [{'name': 'wozozo', 'val': 123}, {'name': 'feiz', 'val': 456}]}
+
 ドット区切りのフィールド指定による参照
 ---------------------------------------
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.