Sunday, January 28, 2018

Re: how do I make django search for male or female without needing to specify an age?

Why do you make a POST request for displaying a list? Use GET parameters like its done for admin filters.
And for building an API that returns JSON Data use DjangoRestFramework and you will just need to define your serializer fields .. the rest is taken care of for you. That code above looks overly complicated!

For instance you define app_name, model_name, method_name in filterchain_all although its not used.
Your are sending male and female intstead of the values itself as a normal django form would have done it.
Dont make a list out of the qs for no reason.
And instead of doing this "if int(item.age) not in [d['display'] for d in final]" over and over again use a set() to not get multiple results.

BUT moreover to get all distinct ages use:
Child.objects.vales_list('age', flat=True).order_by('age')
Done in one single line by your database instead of the handwritten view!

Please have a look at the django tutorial (https://docs.djangoproject.com/en/2.0/intro/tutorial01/) and keep an eye out for how the admin filters things in a way that can be linked from the outside with GET parameters (you cannot linkt to a filtered list that is requested by a post request)

Please stop using Q() in cases where its not neccessary .. all parameters in a queryset do mean AND. You only need a Q for more complex stuff or an actual OR.
Use a class based FormView to erase even more of the handwritten code and secure it with the LoginRequiredMixin.
Please dont ever again use a TemplateView for dynamic content use the render() method like shown in the tutorial!

Once you have completed the tutorial and embraced the concepts your code will be about 1/10 of the above and it will save you a lot of time figuring out how to do things that are already taken care of by Django if only you knew how. :)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5b204908-459a-42bd-970f-c2d45e7ef3db%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment