Rohit D H
Rohit D H

Reputation: 41

How to filter the objects related to foreign key model in django Views.py

I have models.py as like this:

class Subject(models.Model):
    sub = models.CharField(max_length=200)

    slug = models.SlugField(unique=True)
    created_on = models.DateTimeField(auto_now_add=True)

class Post(models.Model):
    sub = models.ForeignKey(Subject, on_delete=models.CASCADE)
    file_name = models.CharField(max_length=50,blank=True)
    url = models.CharField(max_length=800, unique=True)

urls.py

 path('view/<subj>/', views.PostDetail, name='post_detail'),

views.py

def PostDetail(request, subj):
    content = Post.objects.get(sub=subj)

But I'm getting this error when i pass subj as sig from url,

invalid literal for int() with base 10: 'sig'

How to get all the objects related to the query subj i.e "sub" in Post model?

Upvotes: 0

Views: 3314

Answers (2)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

If you are expecting more than one object (queryset) then, use filter():

def PostDetail(request, subj):
    content = Post.objects.filter(sub__sub=subj)

invalid literal for int() with base 10: 'sig' : Because, in your get() method, sub was expecting some kind of id(integer). But, you have passed string. So, by going to specific field inside Subject model and pointing to sub using underscore(__) you should get what you weere expecting.

Lookups using underscore.

Upvotes: 2

Max
Max

Reputation: 876

in your urls.py give subj type, if subj is String add <str:***>:

path('view/<str:subj>/', views.PostDetail, name='post_detail'),

views.py:

def PostDetail(request, subj):
    content = Post.objects.filter(sub__sub=subj)

use filter to search Post.sub, because sub is ForeignKey, so use sub__sub.

Upvotes: 0

Related Questions