Как проверить, создан ли уже объект в функции to_present сериализатора Django rest framework
Мне нужно проверить, создан ли уже объект перед добавлением некоторых данных для просмотра в ответе сериализатора.
мой код
class AppUserSerializer(serializers.ModelSerializer):
'''
Serializing App User model
'''
main_user = MainUserSerializer(read_only=True)
class Meta:
'''
Defining main data for AppUserSerializer
'''
model = AppUser
# fields = "__all__"
fields = [
"first_name",
"last_name",
"mobile",
"email",
"birthdate",
"password",
"confirm_password",
"image",
"main_user",
"generated_code",
"user_langauge",
"dark_mode",
]
def to_representation(self, instance):
'''
Adds more data to be serialized back with AppUserSerializer
'''
data = super().to_representation(instance)
if AppUser.objects.filter().exists(): #need to check if object already there here, what to add inside filter() !!
if instance.playerprofile_set.all().count() > 0:
player_profile = instance.playerprofile_set.all()[0]
data['player_profile'] = PlayerProfileSerializer(
player_profile).data
for item in Team.objects.all():
if player_profile in item.players.all():
data['team'] = TeamSerializer(item).data
if item.cap.id == player_profile.id:
data['team'] = TeamSerializer(item).data
return data
Если экземпляр имеет pk, то он был создан.
Вы можете спросить
if instance.pk: