5
For anyone else coming here who wants a more generalised example of using Factory Boy and django-taggit, the Factory Boy docs include a Many-to-Many example which is useful. So:
import factory
from myapp.models import Experiment
class ExperimentFactory(factory.DjangoModelFactory):
class Meta:
model = Experiment
# other fields here
@factory.post_generation
def tags(self, create, extracted, **kwargs):
if not create:
# Simple build, do nothing.
return
if extracted:
# A list of tags were passed in, use them.
for tag in extracted:
self.tags.add(tag)
Then you can do:
from myapp.factories import ExperimentFactory
ExperimentFactory(name='A Name', tags=['Tag 1', 'Tag 2', 'Another tag',])
Note, this won’t create tags if you do ExperimentFactory.build()
, only if you do ExperimentFactory.create()
or its synonym ExperimentFactory()
.
2
finally found the solution:
@factory.post_generation
def post_tags(self, create, extracted, **kwargs):
self.tags.add(u'abc, cde', u'xzy')
- [Django]-Make a One to Many Relation in django
- [Django]-Error installing a django project AttrributeError: module 'collections' has no attribute 'Iterator'
- [Django]-Django date YYYY-MM-DD
Source:stackexchange.com