I cannot figure out what kind of field shoud I use in my serializer class if in the model it is a ForeignKey
class DotPrivateSerializer(serializers.ModelSerializer):
tag = serializers.________________Field(
queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault())
)
models.py
class DotPrivate(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
name = models.CharField(max_length=255)
description = models.TextField(max_length=350, blank=True)
lon = models.CharField(max_length=20)
lat = models.CharField(max_length=20)
rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(5.0)])
tag = models.ForeignKey('TagPrivate', on_delete=models.PROTECT)
CodePudding user response:
Use SerializerMethodField. The below code will nest the Foreign Key record in the json.
class DotPrivateSerializer(serializers.ModelSerializer):
tag = serializers.SerializerMethodField()
def get_tag(self,obj):
queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault())
return TagPrivateSerializer(queryset).data