Django Model generalized condition - django

How can I add a generalized condition in django models like if I filter using ORM object the condition should automatically get added.
I have done similar in cake PHP and YII where I actually get the query ORM and I can add a condition that gets attached to the query and later the query is fired.
Looking for similar kind of function in Django for Users Model.
User.objects.filter(date_joined__range=(start_date_time, end_date_time))
I want whenever I filter using this it should add a condition to the query.
Answers and suggestions would be appreciated.

Related

In a Django Rest Framework view, does request.user make a database call or the database call happens before the request reaches the view?

I need to retrieve some information about my users and I am trying to avoid making unnecessary database calls.
The information I need is stored in three models: User, UserProfile and Membership.
Both UserProfile and Membership have a OneToOne relationship with the User model.
I know that I can use select_related() to retrieve related models from the database in a single call. So I could do something like:
User.objects.select_related('userprofile').select_related('membership').get(id=request.user.id)
But that must not be correct, because if I am using some user information to do the query, it means I already retrieved this information in a previous call.
So what would be the best way to get this information minimising database calls? Would it be even possible to get the information from these 3 models in a single call?
DRF performs user related DB query inside authentication class. See source here. So if you need to optimize this query you should implement custom autentication class(see details here), override authenticate_credentials method and use optimized query inside it.

How to load django model rows in a list?

I have a django model that I am basically querying on keypress using ajax to find possible matches cause I am avoiding duplicated rows.
Now my question is how can I copy all the rows from a django model and query on it rather than hitting the database every time the user presses a key because I do not think this is a good idea and please correct me if I am wrong.
What are the consequences of hitting a database on keypress?

How can i implement advanced search in django?

How can i implement advanced search like the one below in Django?
Link
When I searched, I don't want the page to be refresh.
What is the best practice for doing that? Ajax, rest framework, or other things...?
Is there a reference?
This question is very vague, so here is an overview of the main steps:
On the frontend, have a form with all the desired filters
On filter update or on form submit, send a GET request to the Django server with all of your parameters encoded in the URL (like a typical GET request)
Then, on the server-side (ie Django), assuming you are using Django Rest Framework:
Create a view/action (through an API View or a Viewset) for your filter research
Extract the filters sent by the frontend which will be located in request.query_params
Perform a request in your database based on those filters:
You know what filters are expected
For each one, if it is not empty, perform an additional filter on your model (Model.objects.filter(X=Y))
Then eventually return the results
There are many ways of doing filtering of a model in Django and DRF:
You can use Q to perform complex queries
You can use the django-filters package to easily add filtering in your viewset based on the received GET parameters

How to check duplicate posts when submitting a new post in Django admin?

I have coworkers to upload posts through Django admin. The problem is they keep making duplicate posts as we've been covering a lot of posts. Is there a way to find out if a post already exists when typing a certain column or submitting?
I searched about that, but didn't get any useful information.
Your business case seems to be a text that is duplicate if it is case sensitive equal.
On a DB and Django Model level you assure unique entries by adding unique:
class MyModel(Model):
my_field = TextField(unique=True)
To check during input you need JavaScript in the client and an AJAX endpoint on the Django server side. It's actually an Autocomplete/Autosuggest functionality for that field. There are several packages that might help you with that. Out of the box, the Django Admin does not support this.

Django Rest Framework Hyperlinked Fields Understanding

I can't seem to grasp the difference between HyperlinkedIdentity and HyperlinkedRelated Fields. I have a few questions that I can't seem to find the answers to online.
What is the actual difference? When would I want to use one vs. the other.
My next question is say I have 2 models, Project and Task.
A Task has a ForeignKey to Project. If I wanted the Project to hyperlink to the tasks within it, which Hyperlink field would I put in the ProjectSerializer? And what field would I put in the TaskSerializer to complement the ProjectSerializer assuming I wanted the tasks to be able to hyperlink back to the Project they are related to?
What is the difference between using the hyperlinked fields vs. just using regular nested serializers? When using hyperlinked fields, can I still filter by pk/id?
Last, What if a model had two hyperlinked relations in the serializer? From what I understand it creates a url field for each hyperlink, would it create two url fields in this case?
Thanks for any clarification you can offer, it will be a huge help towards cementing my understanding on the subject and allowing me to complete my API for my project.
What is the actual difference? When would I want to use one vs. the other.
HyperlinkedIdentityField is an hyperlink field for the current object itself while HyperlinkedRelatedField represent an hyperlink to other instances.
A Task has a ForeignKey to Project. If I wanted the Project to hyperlink to the tasks within it, which Hyperlink field would I put in the ProjectSerializer? And what field would I put in the TaskSerializer to complement the ProjectSerializer assuming I wanted the tasks to be able to hyperlink back to the Project they are related to?
HyperlinkedRelatedField is what you're looking for.
What is the difference between using the hyperlinked fields vs. just using regular nested serializers?
Hyperlinks can be browsed independently from the original resource. Handy if one of them belongs to another system. For example, you'll likely want to use hyperlink to tweets rather than let your server fetch them and them return them nested. Hyperlinks also allows the client to deal with its own caching rather than sending back all the data. Could be handy in case of fetching a list of items that nest the same user.
On the other hand, hyperlinks increase the network request count because it needs to fetch more data.
When using hyperlinked fields, can I still filter by pk/id?
Not sure what you mean here.
What if a model had two hyperlinked relations in the serializer? From what I understand it creates a url field for each hyperlink, would it create two url fields in this case?
Correct. hyperlinked relation are just a representation of a relation. It provides an hyperlink (an uri) to fetch the associated object.
This is useful because you won't need to know the pattern to fetch an object from the id: with a PrimaryKeyRelatedField you'll get the id but are missing the url to fetch the associated object.
This also allows the server to manage its own uri space without the need of updating the clients.
Hope this will help.