1

I have 2 django models:

class TelegramUser(models.Model):
    telegram_id = models.IntegerField()
    telegram_username = models.TextField(max_length=255, default=None, blank=True, null=True)
    first_name = models.TextField(max_length=255, default=None, blank=True, null=True)
    last_name = models.TextField(max_length=255, default=None, blank=True, null=True)
    has_blocked = models.BooleanField(default=False)
class DutyDate(models.Model):
    date = models.DateField(default=None, blank=True, null=True)
    telegram_user = models.ForeignKey(TelegramUser, on_delete=models.SET_NULL, null=True)
    group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, null=True)
    mark = models.FloatField(max_length=255, default=0)
    is_open = models.BooleanField(default=True)

I need to get all users, who has less than 3 assigned DutyDates. Can I do it with one query and how?

1 Answer 1

1

Yes. We first count the number of related DutyDates, and then we filter on that count:

from django.db.models import Count

TelegramUser.objects.annotate(
    nduty=Count('dutydate')
).filter(
    nduty__lt=3
)

Here the __lt lookup [Django-doc] filters such that nduty is (strictly) less than 3. If you want to retain TelegramUsers that have three related DutyDates as well, you can use the __lte lookup [Django-doc].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.