Reputation: 621
I wrote the following code:
class PredictionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Prediction
fields = ["id", "market"]
depth = 1
class FixtureSerializer(serializers.HyperlinkedModelSerializer):
predictions = PredictionSerializer()
class Meta:
model = Fixture
fields = ["sofascore_id", "home", "away", "league", "round", "date", "predictions"]
depth = 1
class FixtureViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint that allows fixture to be viewed or edited.
"""
serializer_class = FixtureSerializer
permission_classes = [permissions.IsAuthenticated]
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
filterset_fields = ("home", "away", "sofascore_id", "statistics")
def get_queryset(self):
date = self.request.query_params.get('date')
queryset = Fixture.objects.all().order_by('-date')
if(date):
queryset = Fixture.objects.filter(date__date=date).order_by('date')
return queryset
Corresponding with the following models:
class Market(models.Model):
name = models.CharField(max_length=200)
class Fixture(models.Model):
sofascore_id = models.CharField(max_length=200)
home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home")
away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away")
league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True)
round = models.CharField(max_length=200, default=None, blank=True, null=True)
date = models.DateTimeField()
statistics = models.ForeignKey(Statistics, on_delete=models.CASCADE, default=None, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return u'{0} - {1}'.format(self.home.name, self.away.name)
class Prediction(models.Model):
market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True)
fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="predictions", null=True, blank=True)
When I make an request to /fixtures, the 'predictions' dictionary is always empty, but when I run some test code with the following statement:
f = Fixture.objects.get(sofascore_id=match).predictions.all()
I get the the following as return value:
<QuerySet [<Prediction: Prediction object (23)>, <Prediction: Prediction object (24)>, <Prediction: Prediction object (25)>, <Prediction: Prediction object (26)>, <Prediction: Prediction object (27)>, <Prediction: Prediction object (28)>]>
What is the issue here and why am I unable to retrieve my predictions using the written code?
Upvotes: 0
Views: 429
Reputation: 8077
You need to specify the attribute many
inside your serializer:
class FixtureSerializer(serializers.HyperlinkedModelSerializer):
predictions = PredictionSerializer(many=True, read_only=True)
class Meta:
model = Fixture
fields = ["sofascore_id", "home", "away", "league", "round", "date", "predictions"]
depth = 1
Upvotes: 1