I have different models in Django linked together:
Projects
Fonts (linked by project_id)
Images (linked by project_id)
etc
When I'm using Project.objects.all() it retrieves all of the information from all the linked tables and query gets very slow. However in specific view I do not even need i.e. Fonts and Images. How can I tell django to skip these models while performing query?
You can use values or values_list for this purpose. That way your queryset will only fetch the columns you want.
Using values
projects_obj = Project.objects.all().values('column_name', 'column_name')
Using values_list
projects_obj = Project.objects.all().values_list('column_name', 'column_name')
Related
I'm new to Django and struggling to find the best/correct way to populate a dropdown list in a ModelChoiceField within a form using a list I have stored in a database.
The basic code below works fine with my view passing the form as context to my template but the drop-down returns a 'dictionary' like list with the ugliness or the brackets, colons and the key name (see the attachment)
from django import forms
from .models import constituency
class ConstituencyForm(forms.Form):
ConstituencySelection = forms.ModelChoiceField(queryset=constituency.objects.all().values('name'))
My questions are:
1/ The purpose of this page will be to select one of 650 areas from the dropdown list and have it highlighted on the map. Is this an appropriate way to approach the task (using a queryset within the form itself)?
2/ How do I clean up this list, it should simply read:-
Aldershot
Aldridge-Brownhills
Altrincham and Sale West
and so on and so on
Your help would be forever appreciated!
Thanks,
Phil #anoobinneed
Using values_list() with flat=True will do it.
Change:
queryset=constituency.objects.all().values('name')
To:
queryset=constituency.objects.all().values_list('name', flat=True)
In a Django app of mine, I need to display, for a list of users (called user_ids), their:
username, avatar and score.
The username is retrieved from the User model, whereas avatar and score are present in the UserProfile model (that has a one-to-one field point to the User model, called user).
Currently my approach is to fetch the full objects (see below), even though I just need 3 attributes from the two models.
What's the most efficient way for me to just retrieve just the required fields, nothing else? Now I know i can do:
usernames = User.objects.filter(id__in=user_ids).values_list('username',flat=True)
scores_and_avatars = UserProfile.objects.filter(user_id__in=user_ids).values_list('score','avatar')
However, these give me separate querysets, so I can't iterate over them as a unified object_list and show each user's username, score and avatar in a Django template. So what would be the most efficient, light-weight way to retrieve and put this information together?
Currently, I'm doing the following to retrieve these three fields: queryset = User.objects.select_related('userprofile').filter(id__in=user_ids)
The most efficient way it's use values, your query will look like this:
usernames = User.objects.filter(id__in=user_ids).values('username', 'userprofile__score', 'userprofile__avatar')
This solution will return dictionary, but you can try to use only instead of values, it'll create django model object with specified fields, but if you will try to access not specified field it'll generate additional query.
usernames = User.objects.filter(id__in=user_ids).select_related('userprofile').only('username', 'userprofile__score', 'userprofile__avatar')
I have 3 separate models. I would like to be able to do a query on all tables and return the object with the latest date. What would be the best approach for this? I currently have them returned in a chain. All of the models contain an auto_now_add DateTimeField. Is it possible to filter the latest created object based on the chained queryset?
article_list = Article.objects.all()
issue_list = Issue.objects.all()
annual_list = Annual.objects.all()
result_list = list(chain(article_list, issue_list, annual_list))
if you want only 1 object you can use max() with key
max(result_list, key=lambda x: x.date) #or whatever the name of the field is (should be same on all models)
on the same fashion if you want the whole list sorted by the date field you can use sorted() and give the above key
I want to use a dynamic field in django means I have one model whose one is what be specified in the other model.
I hope i can explain it to you through example.
I have one model name product and each time a new product is uploaded we have to set some attributes for that and that attributes are specified in the 2nd table means in this product model one field is dynamic which depends on the 2nd table. if i select 'x' in other table then that field is shown here and if i select 'y' then that will be shown here,So that based on that product id and attribute id I can specify the attribute value in 3rd table so that in future i can fetch that value for a specified product.
I have tried this a lot but i do not know how to use dynamic fields in django, So can anybody let me know how i can do this.
Thanks
I recommend you to use django-json-field for that purpose ( https://github.com/derek-schaefer/django-json-field ). It uses only one Text field in your db, but you can access objects in your json like a python objects:
json = JSONField() #in your model
json = "{'attributes':{'colour':'blue','size':'2'}, 'image-height':'200px'}" # in your db
{{product.json.attributes}} #in your template
product.json.attributes #in your views
It's a great way to make many 'django' fields, while storing it only in one Text field in db.
The disadvantages of this approach is that you can't effectively search for the fields using your database, but if you have a few dozens of products, you can do the filter by python right in view.
Using Django 1.2.3, I need to update a model field with a ranking among an ordered set of instances, without having to retrieve the entire queryset and update each model by hand.
Is there a way to achieve that?
I think this is what you need: http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once