当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to filter objects in django by hyperlink related field

问题描述:

I have a model called car which contains a property session which is a HyperLinkRelatedField

I am trying to filter the objects by that hyperlinkrelated field

I tried something like this:

session_url = "http://localhost:8000/v1/sessions/"+uuid+"/"

print cars.objects.filter(session=session_url)

I got this error:

ValueError: invalid literal for int() with base 10: 'http://localhost:8000/v1/sessions/4c597c05-5e66-11e6-a79c-9801a78ed96d/'

The problem is, session is definetly not an integer, so I can not understand why this happens

here is how my serializer looks

class CarSerializer(serializers.Serializer):

altitude = serializers.FloatField()

course = serializers.FloatField()

session = serializers.HyperlinkedRelatedField(

many=False,

queryset=Session.objects.all(),

view_name="session-detail",

lookup_field="uuid"

)

timestamp = serializers.DateTimeField(required=False)

Any reason why this is not working ? and if it is wrong then how do we filter an object by a HyperLink in django

网友答案:

You field session is a serializer field, not a model field. In the DRF these fields are usually computed based on the model data. The HyperlinkedRelatedField offers an easy way of putting URLs to ressourses into a response. On the other other hand it contais too much hard to parse data to use it for queries to the ORM. To filter by a relation you need an object of the type the relation goes to or a value with the same type as the primary key. In your case an integer.

To solve your problem, I advise to use a PrimaryKeyRelatedField instead of or in addition to your HyperlinkedRelatedField.

Seeing your code, an other solution could be to filter by the UUID, but you did not provide your models, so I can give a proper code example.

分享给朋友:
您可能感兴趣的文章:
随机阅读: