如何在Django Rest Framwork中获得具有父模型的Forein键的子模型?

时间:2019-03-07 19:34:28

标签: python django django-rest-framework

现在我想要输出这样一种方式,对于每个列表,我都必须获得完整的时序记录,以及如何实现它 下面是我的模特

model.py
class Refreshment(models.Model):
     title = models.CharField(max_length=200, unique=True)
     charges = models.DecimalField(max_digits=12, decimal_places=2, help_text="Charges per hour")





class Timeing(models.Model):
    refreshment = models.OneToOneField(Refreshment,on_delete=models.CASCADE)
     sunday_open = models.TimeField(blank=True, editable=True)

下面是我的views.py

@api_view()
def all_games_sports(request):
  entertainment = Refreshment.objects.filter(type=1)
  serialize = EntertainmentSerializer(instance=entertainment, many=True)
  main = {'status': True, 'code': "CODE_SUCCESSFUL", 'msg': "SUCCESS", 'all_games_sports': serialize.data}
  return Response(main)

Serializer.py

class TimeingSerializer(serializers.ModelSerializer):
   class Meta:
      model = Timeing
      fields = '__all__'

class EntertainmentSerializer(serializers.ModelSerializer):
      refreshment =   TimeingSerializer(many=True,read_only=True)

  class Meta:
      model = Refreshment
      fields = '__all__'

AttributeError: Got AttributeError when attempting to get a value for    field `refreshment` on serializer `AvailableHourSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Refreshment` instance.
Original exception text was: 'Refreshment' object has no attribute 'refreshment'.

1 个答案:

答案 0 :(得分:1)

您的代码引发错误。这应该。您定义了refreshment,但没有将其添加到字段中。

class EntertainmentSerializer(serializers.ModelSerializer):
      refreshment =  TimeingSerializer(many=True,read_only=True)

      class Meta:
          model = Refreshment
          fields = '__all__' #You have not added refreshment to fields.

您应该改为这样做:

class EntertainmentSerializer(serializers.ModelSerializer):
      timeing =   TimeingSerializer(many=True,read_only=True)

      class Meta:
          model = Refreshment
          fields = '__all__'