Django: filter() or get()
Is the way I write discount_code.first().is_active()
the right way, or is it preferable to work with .get
as (discount) code is a code unique field per event? Different events can have the code.
def clean_code(self):
input_code = self.cleaned_data['code']
# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available
anymore."),
code='code_not_active')
return input_code
python django
add a comment |
Is the way I write discount_code.first().is_active()
the right way, or is it preferable to work with .get
as (discount) code is a code unique field per event? Different events can have the code.
def clean_code(self):
input_code = self.cleaned_data['code']
# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available
anymore."),
code='code_not_active')
return input_code
python django
add a comment |
Is the way I write discount_code.first().is_active()
the right way, or is it preferable to work with .get
as (discount) code is a code unique field per event? Different events can have the code.
def clean_code(self):
input_code = self.cleaned_data['code']
# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available
anymore."),
code='code_not_active')
return input_code
python django
Is the way I write discount_code.first().is_active()
the right way, or is it preferable to work with .get
as (discount) code is a code unique field per event? Different events can have the code.
def clean_code(self):
input_code = self.cleaned_data['code']
# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available
anymore."),
code='code_not_active')
return input_code
python django
python django
edited Nov 14 '18 at 16:36
Joel
1,5686719
1,5686719
asked Nov 14 '18 at 16:08
Joey CoderJoey Coder
3069
3069
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You can save a query here. The return value of .first()
on the queryset has all the info you need for your validation:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
Using exists()
is only beneficial if you do not need to process the queryset any further (which you do in the is_active
check). And even then, you need large amounts of data to see real performance gains.
As the statement says, "Explicit is better than implicit". To me, seeingfilter
means "it can return multiple values", andget
means "it should return one value". So I find strange doingfilter().first()
instead ofget
.
– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness ofcode
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).
– schwobaseggl
Nov 14 '18 at 17:22
add a comment |
I would have written the code this way:
def clean_code(self):
input_code = self.cleaned_data['code']
try:
discount_code = self.event.discounts.get(code=input_code)
except Discount.DoesNotExist: # suppose your model is named Discount
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304392%2fdjango-filter-or-get%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can save a query here. The return value of .first()
on the queryset has all the info you need for your validation:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
Using exists()
is only beneficial if you do not need to process the queryset any further (which you do in the is_active
check). And even then, you need large amounts of data to see real performance gains.
As the statement says, "Explicit is better than implicit". To me, seeingfilter
means "it can return multiple values", andget
means "it should return one value". So I find strange doingfilter().first()
instead ofget
.
– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness ofcode
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).
– schwobaseggl
Nov 14 '18 at 17:22
add a comment |
You can save a query here. The return value of .first()
on the queryset has all the info you need for your validation:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
Using exists()
is only beneficial if you do not need to process the queryset any further (which you do in the is_active
check). And even then, you need large amounts of data to see real performance gains.
As the statement says, "Explicit is better than implicit". To me, seeingfilter
means "it can return multiple values", andget
means "it should return one value". So I find strange doingfilter().first()
instead ofget
.
– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness ofcode
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).
– schwobaseggl
Nov 14 '18 at 17:22
add a comment |
You can save a query here. The return value of .first()
on the queryset has all the info you need for your validation:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
Using exists()
is only beneficial if you do not need to process the queryset any further (which you do in the is_active
check). And even then, you need large amounts of data to see real performance gains.
You can save a query here. The return value of .first()
on the queryset has all the info you need for your validation:
def clean_code(self):
input_code = self.cleaned_data['code']
# this is None if it doesn't exist
discount_code = self.event.discounts.filter(code=input_code).first()
if not discount_code:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
Using exists()
is only beneficial if you do not need to process the queryset any further (which you do in the is_active
check). And even then, you need large amounts of data to see real performance gains.
edited Nov 14 '18 at 16:49
answered Nov 14 '18 at 16:43
schwobasegglschwobaseggl
37.4k32442
37.4k32442
As the statement says, "Explicit is better than implicit". To me, seeingfilter
means "it can return multiple values", andget
means "it should return one value". So I find strange doingfilter().first()
instead ofget
.
– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness ofcode
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).
– schwobaseggl
Nov 14 '18 at 17:22
add a comment |
As the statement says, "Explicit is better than implicit". To me, seeingfilter
means "it can return multiple values", andget
means "it should return one value". So I find strange doingfilter().first()
instead ofget
.
– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness ofcode
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).
– schwobaseggl
Nov 14 '18 at 17:22
As the statement says, "Explicit is better than implicit". To me, seeing
filter
means "it can return multiple values", and get
means "it should return one value". So I find strange doing filter().first()
instead of get
.– mistiru
Nov 14 '18 at 17:05
As the statement says, "Explicit is better than implicit". To me, seeing
filter
means "it can return multiple values", and get
means "it should return one value". So I find strange doing filter().first()
instead of get
.– mistiru
Nov 14 '18 at 17:05
@mistiru I don't disagree, given the uniqueness of
code
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).– schwobaseggl
Nov 14 '18 at 17:22
@mistiru I don't disagree, given the uniqueness of
code
. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if
).– schwobaseggl
Nov 14 '18 at 17:22
add a comment |
I would have written the code this way:
def clean_code(self):
input_code = self.cleaned_data['code']
try:
discount_code = self.event.discounts.get(code=input_code)
except Discount.DoesNotExist: # suppose your model is named Discount
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
add a comment |
I would have written the code this way:
def clean_code(self):
input_code = self.cleaned_data['code']
try:
discount_code = self.event.discounts.get(code=input_code)
except Discount.DoesNotExist: # suppose your model is named Discount
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
add a comment |
I would have written the code this way:
def clean_code(self):
input_code = self.cleaned_data['code']
try:
discount_code = self.event.discounts.get(code=input_code)
except Discount.DoesNotExist: # suppose your model is named Discount
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
I would have written the code this way:
def clean_code(self):
input_code = self.cleaned_data['code']
try:
discount_code = self.event.discounts.get(code=input_code)
except Discount.DoesNotExist: # suppose your model is named Discount
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
if not discount_code.is_active():
raise forms.ValidationError(_("This discount code is not available anymore."),
code='code_not_active')
return input_code
answered Nov 14 '18 at 16:58
mistirumistiru
440113
440113
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304392%2fdjango-filter-or-get%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown