Helper function to improve code

This commit is contained in:
2020-05-21 18:05:08 +02:00
parent 8e6a36212d
commit 29fb109b6f

View File

@@ -11,7 +11,7 @@ T = TypeVar('T', bound=django.db.models.Model)
def create(model: Type[T], **kwargs) -> T:
if model is models.Video:
return models.Video.objects.create(**{**dict(title='Title', slug='slug', description='Description'), **kwargs})
return _create_with_defaults(models.Video, kwargs, title='Title', slug='slug', description='Description')
if model is models.Transcoding:
video = create(models.Video, title='Title', slug='slug', description='Description') \
@@ -25,12 +25,19 @@ def create(model: Type[T], **kwargs) -> T:
# only URL if no upload for they are multually exclusive
defaults['url'] = 'https://some_url'
return models.Transcoding.objects.create(**{**defaults, **kwargs})
return _create_with_defaults(models.Transcoding, kwargs, **defaults)
if model is models.Upload:
file = SimpleUploadedFile('some_file.txt', b'some contents') \
if 'file' not in kwargs else None
return models.Upload.objects.create(**{**dict(file=file), **kwargs})
return _create_with_defaults(models.Upload, kwargs, file=file)
# TODO fix annoying dict notation to something more gentle.
def _create_with_defaults(model: Type[T], kwargs: dict, **defaults) -> T:
"""
Return created django model instance.
:param model: django model to create
:param kwargs: keyword arguments to fill the model
:param defaults: default keyword arguments to use when not mentioned in kwargs
"""
return model.objects.create(**{**defaults, **kwargs})