fnatic_shank
fnatic_shank

Reputation: 607

Django - Filter QuerySet in models.py

Is is possible to make queries from django models?

I have 2 models:

class Book(models.Model):
    ...
    def copies_available(self):
        pass

and

class BookCopy(models.Model):
    ...
    book_category = models.ForeignKey(Book, related_name='copies')
    issued_to = models.ForeignKey(EndUser, related_name='issued_books', null=True, blank=True)

I want copies_available() to return the number of BookCopy intances of that Book whose issued_to is None

Upvotes: 2

Views: 2136

Answers (3)

guinunez
guinunez

Reputation: 150

I did this a couple years ago, so it may have changed a little bit:

You nee to create a BookManager class, and put the functionality there. Then assign the manager to your Book model's object variable, like this:

class BookManager(models.Manager):

    def copied_available(self):

        queryset = BookCopy.objects.filter(book_category=self.id).filter(issued_to is not None)

        return queryset.count()

class Book(models.Model):
    ...
    objects = BookManager()

So in your template, you can do something like:

<p> Copies: {{ thebook.copied_available }}</p>

Upvotes: 0

mariodev
mariodev

Reputation: 15484

This should work:

class Book(models.Model):
    ...
    def copied_available(self):
        return self.copies.filter(issued_to__isnull=True).count()

Upvotes: 2

Garry Cairns
Garry Cairns

Reputation: 3115

Yes just set limit_choices_to in the ForeignKey. From the docs:

"A dictionary of lookup arguments and values (see Making queries) that limit the available admin or ModelForm choices for this object. Use this with functions from the Python datetime module to limit choices of objects by date. For example:"

limit_choices_to = {'pub_date__lte': datetime.date.today}

Upvotes: 0

Related Questions