Source code for services.posts.tags
from apps.posts.models import Tag
[docs]
class TagService:
[docs]
@staticmethod
def get_or_create_tags(tag_names: list) -> list:
# Retrieve existing tags by name
existing_tags = Tag.objects.filter(name__in=tag_names)
existing_tag_names = existing_tags.values_list("name", flat=True)
# Determine which tags you need to create
new_tag_names = set(tag_names) - set(existing_tag_names)
# Create new tags
new_tags = Tag.objects.bulk_create([Tag(name=name) for name in new_tag_names])
return list(existing_tags) + new_tags