Home > Mobile >  How to filter objects by value of one of its fields in django?
How to filter objects by value of one of its fields in django?

Time:12-19

I have django application with urls.py:

path('<str:slug>/', views.article),

When user types name of product in my website, the view is triggered:

def article(request, slug):
    videos = models.Video.objects.filter(article=slug)
    return render(request, 'videos/at_detail.html', {'videos': videos})

If I add print(slug) somewhere in function it returns the word I entered in url, so this part works.

models:

class article(models.Model):
    name = models.CharField(max_length=30, null=True)
    slug = AutoSlugField(populate_from='name', unique=True, default=None)
    created_on = models.DateTimeField(default=timezone.now)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, default=None)
    
    def __str__(self):
        return self.name
    

    class Meta:
        verbose_name = "Articles"


class Video(models.Model):
    video_id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False
    )
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    file = models.FileField()
    article = models.ForeignKey(at, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.title)   " - "   str(self.at)

    class Meta:
        verbose_name_plural = "Videos"
        verbose_name = "Video"

What doesn't work, and what I'm trying to do, is to get all objects, which have same value 'article', that what I entered in my url. So for example: if I type 127.0.0.1:8000/blueberry/ I will get all objects with field article=blueberry.

Is this possible and if it is, how can I do that?

Edit #1

Instead of videos = models.Video.objects.filter(article=slug) I wrote videos = models.Video.objects.filter(at__slug=slug) as @AnkitTiwari commented. It gets rid of error but if I print(videos) I get empty query set: <QuerySet []>. I have videos in my database though. If I do videos = models.Video.object.all() and print(videos.title) I get title of one video in my database. If I do this thing with 2 videos I get an error, which says I can't display title of 2 elements. But I get query set with info of 2 videos.

So, why is my query set empty although I have videos in my database?

CodePudding user response:

Have you tried Video.objects.filter(article__slug__iexact=slug) ?

  • Related