2

So I have a get function

class HorseEquipmentView(APIView):
    lookup_url_kwarg = 'horse'

    def get (self, request, format = None):
        horse = 1     
        if horse != None:
            tab = []
            #queryset = HorseEquipment.objects.raw('SELECT H.horse_id, E.name FROM horse_equipment H JOIN equipment E ON H.equipment_id = E.id WHERE H.horse_id =' + str(horse))
            queryset = HorseEquipment.objects.filter(horse_id=horse).select_related("equipment")
            for i in queryset:
                i.equipment = Equipment.objects.filter(id = 1).name  
            #equipment = HorseEquipment.objects.filter(horse_id=horse).select_related('equipment')
            serializer = HorseEquipmentSerializer(queryset, many = True)
            return Response(serializer.data)
        else:
            return Response(status = status.HTTP_400_BAD_REQUEST)

and my Equipment Model:

class Equipment(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(unique=True, max_length=30, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'equipment'

So it has id and name attributes but somehow it gives me error on my get function, precisely on my for loop where I refer to "name" attribute. Can you help me find out what's wrong?

1
  • You need to re-read the section about objects.filter(...) vs objects.get(...). Commented May 15, 2021 at 7:47

1 Answer 1

3

You're using .filter() which will return a QuerySet and not a instance of a model. You should use .get() for this scenario to access the name attribute.

Replace:

Equipment.objects.filter(id=1).name 

With

Equipment.objects.get(id=1).name 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.