Search code examples
djangodjango-modelsdjango-testsfactory-boy

How to write a factory for this model in django using factory_boy?


I have a model in my app that contains many_to_many fields on the same model but with a filter. To be more clear this is what I have:

class Places(models.Model):
     user = models.OneToOneField('User')
     common_kwargs = dict(to='places.Place', blank=True)
     place1_kwargs = dict(
     common_kwargs.items() + {
        'limit_choices_to': {'site__token': 'site1'},
        'related_name': '%(app_label)s_%(class)s_place1',
        'verbose_name': _('Place 1')
        }.items()
    )
    place1= models.ManyToManyField(**place1_kwargs )

       place2_kwargs = dict(
       common_kwargs.items() + {
        'limit_choices_to': {'site__token': 'site2'},
        'related_name': '%(app_label)s_%(class)s_place2',
        'verbose_name': _('Place 2')
        }.items()
    )
    place2 = models.ManyToManyField(**place2_kwargs)

and this is Place model in places app :

class Place(models.Model):
     site= models.ForeignKey(Site, verbose_name=_('Site'))
     name = models.CharField(verbose_name=_('Name'),unique=True, max_length=255, db_index=True)
     city = models.CharField(max_length=255, verbose_name=_('City'), null=True)

And this is Site model :

 class Site(models.Model):
     token = models.CharField(_('Token'), max_length=255, unique=True, editable=False)
     name = models.CharField(_('Name'), max_length=255)

I tried to create a Factory for Places model but I didnt know how to set the filter of Site?

Could Somebody help me on this ?? Thanks in advance.


Solution

  • You should create the SiteFactory as well and use a SubFactory because it is a ForeignKey. Hope this helps:

    class PlacesFactory(DjangoModelFactory):
        class Meta:
            model = Places
    
            site = factory.SubFactory(SiteFactory)
    
        @factory.post_generation
        def place1(self, create, extracted):
            if not create:
                return
            if extracted:
                for place in extracted:
                    self.place1.add(place)
    

    Here you can find the official documentation of SubFactory.