Home > Enterprise >  Django filter by category
Django filter by category

Time:05-05

i want to see specific category wise post, i created category app and blog app.i want show top 5 or 10 post in home.html.that's why i need 4 specific category. but i can't filter(category) from post model.i cant access category because i created it another app..

i want to filter by category.

model.py for category

class Category(models.Model):
 parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True)
 category_name = models.CharField(max_length=50,unique=True)
 slug = models.SlugField(allow_unicode=True,max_length=100,unique=True)
 description =models.TextField(max_length=300,blank=True)
 cat_image = models.ImageField(upload_to = 'photo/categories',blank = True)
 created_at = models.DateTimeField(auto_now_add=True)

model.py for blog

class Post(models.Model):
 title = models.CharField(max_length=200, unique=True)
 slug = models.SlugField(allow_unicode=True, unique=True, max_length=250, null=True, blank=True)
 subtitle = models.CharField(max_length=255, blank=True)
 heder_image =  models.ImageField(null=False,blank=True,upload_to="images/")
 heder_image_url =  models.CharField(null=True,blank=True,max_length=200)
 heder_image_Under_line =  models.TextField(null=True,default="image")
 # author = models.ForeignKey(Profile, on_delete=models.PROTECT)
 author = models.ForeignKey(User, on_delete=models.CASCADE)
 updated_on = models.DateTimeField(auto_now= True)
 created_on = models.DateTimeField(auto_now_add=True)
 body   = RichTextField(max_length=100000)
 status = models.IntegerField(choices=STATUS, default=0)
 meta_description = models.TextField(max_length=300, blank=True,default='')
 category = models.ForeignKey(Category,on_delete= models.CASCADE)

views.py

def home(request):
 category = Category.objects.all().filter(parent=None)
 post_by_category = Post.objects.filter(published=True).order_by('-created_on')#filter by category name
 slider = Post.objects.filter(slider=True).order_by('-created_on')


 context = {
      'category':category,
      'post_by_category':post_by_category,
      'slider':slider,
      'counter':Counter,
 }
 return render(request,'home.html',context)

CodePudding user response:

Django also supports a special __ (double underscore) syntax to follow relationships when filtering. So the following should also work:

post_by_category = Post.objects.filter(category__category_name="aaa", published=True)

CodePudding user response:

post_by_category = Post.objects.filter(category=Category.objects.get(category_name="aaa"))

This should work if you want filter post by specific category name.

  • Related