简体   繁体   中英

Filtering on foreign keys

I generate QuerySet as follows:

def get_queryset(self):
    return Article.objects.filter(foreignkey=self.kwargs['value'])

The value is generated like this:

<a href="{% url 'someview' value %}">anchor</a>
url(r'^(?P<value>\w+)/$', someview.as_view(), name='someview')

When value is integer then everything works, but when I pass value as a string I receive:

ValueError: "invalid literal for int() with base 10"

You are passing string to the foreign key's primary key which is integer by default. If you want to filter based on foreign key field use

def get_queryset(self):
    return Article.objects.filter(foreignkey__valuefield=self.kwargs['value'])

Source https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

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