pythondjangounit-testingdjango-parler

django parler create test objects


I have models that have translatable fields using Django Parler and now I am trying to create objects for unit testing. Here is an example model that I have

class Federation(TranslatableModel):
    translations = TranslatedFields(
        name = models.CharField('name', max_length=50)
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='federation_creator')
    updater = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='federation_updater')

    def __str__(self):
        return self.name;

Now I want to create objects for testing during setUp phase of test case:

 Federation.objects.create(...)

but I don't know how to create objects with translatable fields.

How can I achieve this?


Solution

  • You can do this in the way the Parler documentation suggests throughout:

    f = Federation()
    
    f.set_current_language('en')
    f.name = 'The British'
    
    f.set_current_language('fr')
    f.name = 'Les rosbifs'
    
    f.save()
    

    But you can also do:

    f = Federation.objects.language('en').create(
        name='The British',
    )
    
    f.set_current_language('fr')
    f.name = 'Les rosbifs'
    
    f.save()
    

    which is what you're asking about and is more elegant, especially if you only have one language version to create.

    I discovered the language('en') method here.