SebastianM6L,
@SebastianM6L@mastodon.social avatar

Why isn't

Model.objects.get_or_none()

a thing in #django ?

That would save some boilerplate code or am I wrong?

Because if there is a chance that there is no entry for the query get()will raise a DoesNotExist exception that you have to catch.

get_or_none()would be cleaner in my opinion.

benjaoming,
@benjaoming@social.data.coop avatar

@SebastianM6L you can use .first() if you don't care about MultipleObjectsReturned issues. Otherwise, I think it's best to define your own logic for your particular case. I wouldn't like the framework to "trick" people, so I think the current behavior is really good 😇

adamchainz,
@adamchainz@fosstodon.org avatar

@SebastianM6L Many duplicate closed tickets asking about this:

https://duckduckgo.com/?t=ffab&q=site%3Acode.djangoproject.com+get_or_none&ia=web

Also, I’ve seen several packages implement it. I think it could be a worthwhile forum discussion, at laest to gather more opinions. I suggest you start a thread on https://forum.djangoproject.com :)

SebastianM6L,
@SebastianM6L@mastodon.social avatar

@adamchainz Thanks for the feedback. One of this tickets is mine. I honestly did not search for the closed tickets and thought my idea would be a novelty 🤦‍♂️

I still think it would be useful.

I will start a thread in the forum if there is not already one. Will prepare my example first to make the problem clearer.

Again thanks for your feedback. It's not that easy for first time contributors to manoeuvre around all that.

adamchainz,
@adamchainz@fosstodon.org avatar

@SebastianM6L Yeah it’s hard to dive into such a long-running project. We’re all here to help. Ping me with your forum thread 😀

oliverandrich,
@oliverandrich@fosstodon.org avatar

@SebastianM6L Models.object.filter(…).first() does the same, or do you have something else in mind?

SebastianM6L,
@SebastianM6L@mastodon.social avatar

@oliverandrich yeah I kinda don't like the filter().first() approach.

I thought about .get_or_none() method.

That would return you an object only if there is exactly one and return None if not.
Should raise also MultipleExeption if there are more than one object found by the query.

I know it's kind of a special problem. 🤔

oliverandrich,
@oliverandrich@fosstodon.org avatar

@SebastianM6L Ah, I see. I like the MultipleException part. I would love to have that as a function for managers.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • django
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • megavids
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • anitta
  • Leos
  • tester
  • provamag3
  • JUstTest
  • All magazines