Biju
Biju

Reputation: 195

Django range filter with condition

I have a model and manager as follows, here I want to filter published posts in a date range if dates are given, otherwise I want to show only published posts.

class Video(ModelMeta, models.Model):
    category = models.ForeignKey(VideoCategory, on_delete=models.CASCADE, related_name='videos', blank=True, null=True)
    video_title = models.CharField(verbose_name='Title', max_length=120, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    title = EmbedVideoField(
        verbose_name='Either Choose video from youtube/vimeo or',
        blank=True,
        null=True)
    publish = models.CharField(verbose_name='Visibility',
                               max_length=80, choices=PUBLISH_CHOICES, default='publish')
    is_active = models.BooleanField(default=True)
    publish_start = models.DateTimeField(blank=True, null=True)
    publish_end = models.DateTimeField(blank=True, null=True)

    objects = VideoManager()
    
    
class VideoManager(models.Manager):
    def active(self):
        return self.get_queryset().filter(is_active=True)
    
    def active_range(self):
        return self.get_queryset()\
            .filter(publish_end__gte=timezone.now(), publish_start__lte=timezone.now()) \
            .filter(publish='publish') 
            
    def published(self):
        return self.active().filter(publish='publish') 

How I can do it, and combine the distinct values

Upvotes: 0

Views: 84

Answers (1)

ruddra
ruddra

Reputation: 51978

You can try like this:

def active_and_published(self):
    return self.active_range() | self.get_queryset().filter(publish_start__isnull=True, publish_end__isnull=True,publish='publish')

More information can be found in OR operation in queryset in Django.

Upvotes: 1

Related Questions