DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Async Support in Django
  • Post-Migration Modernization: When and How to Refactor
  • Relate, Jev, and MCP: A Judgment Ledger for Agent Decisions
  • The Query Takes 20 ms. Why Does the API Take Two Seconds?

Trending

  • Using Middleware in LangChain: Recovering From Tool Failures
  • The Rise of the Unsanctioned Agent Swarm
  • Building an AI-Powered Code Review Assistant in Java
  • Your Infrastructure Didn't Change, Your Policy Did: Detecting Governance-Transition Drift in IaC

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Adding a .first() method to Django's QuerySet

Adding a .first() method to Django's QuerySet

By 
Chase Seibert
·
Mar. 19, 12 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers.first, which takes a query set and returns the first element, or None if the query set was empty.

Instead of writing this:

try:
    object = MyModel.objects.get(key=value)
except model.DoesNotExist:
    object = None

You can write this:

def first(query):
    try:
        return query.all()[0]
    except:
        return None

object = helpers.first(MyModel.objects.filter(key=value))

Note, that this is not identical. The get method will ensure that there is exactly one row in the database that matches the query. The helper.first() method will silently eat all but the first matching row. As long as you're aware of that, you might choose to use the second form in some cases, primarily for style reasons.

But the syntax on the helper is a little verbose, plus you're constantly including helpers.py. Here is a version that makes this available as a method on the end of your query set chain. All you have to do is have your models inherit from this AbstractModel.

class FirstQuerySet(models.query.QuerySet):

    def first(self):
        try:
            return self[0]
        except:
            return None


class ManagerWithFirstQuery(models.Manager):

    def get_query_set(self):
        return FirstQuerySet(self.model)


class AbstractModel(models.Model):
    objects = ManagerWithFirstQuery()

    class Meta:
        abstract = True


class MyModel(AbstractModel):
    ...

Now, you can do the following.

object = MyModel.objects.filter(key=value).first()

 

Database Django (web framework)

Published at DZone with permission of Chase Seibert. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Async Support in Django
  • Post-Migration Modernization: When and How to Refactor
  • Relate, Jev, and MCP: A Judgment Ledger for Agent Decisions
  • The Query Takes 20 ms. Why Does the API Take Two Seconds?

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook