I am implementing an API for an image labelling app. I have customised a create() method for Tagging. A Tagging contains a tag, which is an object containing a name and a language. To make tags easier to compare to each other, I have to save all tags either in upper or lower case.
serializers.py
def create(self, validated_data):
"""Create and return a new tagging"""
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag'] = tag
tagging = Tagging(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
tag=validated_data.get("tag"),
created=datetime.now(),
score=score,
origin=""
)
tagging.save()
return tagging
I have tried both this
tag=validated_data.get("tag").upper()
and this:
tag=validated_data.get("tag").lower()
and I get an AttributeError 'Tag' object has no attribute 'upper' or 'Tag' object has no attribute 'lower'.
I want for this tag in the tagging object:
{
"gameround_id": 65,
"resource_id": 11601,
"tag": {
"name": "TagToTestNow",
"language": "de"
}
}
to be saved something like "TAGTOTESTNOW" or "tagtotestnow" to make Tag comparison easier.
How can I achieve this?
CodePudding user response:
It's because you already created the tag, so it's not a dict anymore. You can do tag=tag
directly in you Tagging
object creation.
If you want all your tags to have the same case, you have to slightly modify the way you create your Tag in the first place, as follow:
tag = Tag.objects.get_or_create(
language=tag_data['language'],
name=tag_data['name'].upper()
)[0]