简体   繁体   中英

DRF PrimaryKeyRelatedField, AttributeError: 'QuerySet object has no attribute parameter'

I'm trying to get a REST-backend up and running, my first in Python. An incident can have many UnderWays but an UnderWay may only have one Incident(ManyToOne).

I'm now trying to get the serializer for the UnderWay model to work, it should do both POST and GET requests with the following parameters['incident', 'phonenumber', 'time'].

It feels as if I've tried everything but all I get is an AttributeError saying 'QuerySet' object has no attribute 'incident'.

models.py:

class Incident(models.Model):
active = models.BooleanField(default=False)
message = models.TextField(max_length=200, blank=True)
time = models.TimeField(auto_now=False, auto_now_add=False)
created_at = models.DateTimeField(auto_now=True, auto_created=True)
updated_at = models.DateTimeField(auto_now=True)


class UnderWay(models.Model):
    id = models.BigAutoField(primary_key=True)
    incident = models.ForeignKey(Incident, null=True)
    telephone = models.CharField(max_length=30, blank=True)
    time = models.CharField(max_length=30, blank=True)
    created_at = models.DateTimeField(auto_now=True, auto_created=True)

views.py

class LastIncidentApiView(generics.ListCreateAPIView):
"""This class defines the create behavior of our rest api."""
queryset = [Incident.objects.order_by('created_at')[0]]
serializer_class = IncidentSerializer

def perform_create(self, serializer):
    """Save the post data when creating a new incident."""
    serializer.save()


class UnderWayApiView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    # active = Incident.objects.latest('created_at').pk
    queryset = [UnderWay.objects.all()]
    serializer_class = UnderWaySerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new incident."""
        serializer.save()

serializers.py

class IncidentSerializer(serializers.ModelSerializer):

class Meta:
    """Meta class to map serializer's fields with the model fields."""
    model = Incident
    fields = ('id', 'active', 'message',
               'time',
              'created_at', 'updated_at')
    read_only_fields = ('created_at', 'updated_at')


class UnderWaySerializer(serializers.ModelSerializer):
    incident = serializers.PrimaryKeyRelatedField(queryset=Incident.objects.all().values_list('pk', flat=True))

    class Meta:
        model = UnderWay
        fields = ('incident', 'telephone', 'time', 'created_at')
        read_only_field = 'created_at'

I do however get the GET-requests to work if I make the incident field in the serializer a ReadOnlyField. But that's not really helping me a lot.

Thankful for any help :)

Change this line in your serializer,

incident = serializers.PrimaryKeyRelatedField(queryset=Incident.objects.all())

And in your view,

queryset = UnderWay.objects.all()

For a cleaner code, you should define a IncidentApiView with

queryset=Incident.objects.all()

and no perform_create (useless IMO, as what you're doing comes from the Create part of ListCreateAPIView)

LastIncidentView could be a ListAPIView where you override perform_read to get only the last one (there's no reason to POST a "Last Incident", you only want to POST an incident, which at a time will be the current last)

For UnderWayApiView, queryset should be

UnderWay.objects.all()

For UnderWaySerializer,

incident = serializers.PrimaryKeyRelatedField(queryset=Incident.objects.all())

should be better

I'm not saying that it will fix your problem, but it should be more respectful of what DRF expects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM