Aaeronn
Aaeronn

Reputation: 155

search query result in django

Here is my model

class News(models.Model):
    title = models.CharField(max_length=500)
    published_date = models.CharField(max_length=100)
    description = models.TextField()
    details = models.TextField()
    status = models.BooleanField(default=False)
    crawler = models.ForeignKey('Crawler')
    category = models.ForeignKey('Category')

And the view for the news is

class DisplayNewsView(TemplateView):

template_name = "news_listing.html"
#paginate_by = 10


def get_context_data(self, **kwargs):

    context = super(DisplayNewsView, self).get_context_data(**kwargs)


    categories_list = Category.objects.all().filter(created_by=self.request.user)

    context['news_list'] = []
    for categories in categories_list:
        print(categories)
        for crawler in categories.crawlers.get_queryset():  
            #print(categories)
            print(crawler)          
            crawler_list = News.objects.filter(
                    Q(category=categories), 
                    Q(crawler=crawler) | Q(crawler=crawler))
            #print(crawler_list)
        context['news_list'].append(crawler_list)
    return context

I have displayed the news in template. I want to search the news according to time. I mean the news from "date" to "date" as per the published date in news model.

My model for category is

class Category(models.Model):

    category = models.CharField(max_length=50)
    identifier = models.CharField(max_length=50, unique=True)
    level_1_words = models.TextField()
    level_2_words = models.TextField()
    created_by = models.ForeignKey(User,null=True)
    crawlers = models.ManyToManyField('Crawler',related_name='crawler_name')

    class Meta:
        verbose_name_plural = "Categories"

    def __unicode__(self):  # Python 3: def __str__(self):
        return self.category

Can anyone plz help to to search the news according to publish date. I want it to be done like from "date" to "date" submit. When user click the submit button I want the news to be filtered..

It would be great help if someone tell me how to download the searched news in csv too. thanx in advance

Upvotes: 0

Views: 220

Answers (1)

bhappy
bhappy

Reputation: 62

You first need to make that field of the date a DateField instead of CharField

This is how to query date range in django

News.objects.filter(pub_date__lte=datetime(2014, 5, 30), pub_date__gte=datetime(2014, 1, 30))

Another example would be

News.objects.filter(pub_date__lte=datetime(2014, 5, 30), pub_date__gte=datetime(2014, 1, 30)).exclude(datetime.date.today())

for more information on django queries check out the docs @ Making queries in Django

Upvotes: 1

Related Questions