How do I get a specific field in Django query? - python

I'm trying to query only a specific field in Django model. After some searching, I figured out that I need to use only(). However I need to use filter(authuser=request.user) as well. How do I make it possible? Thank you.

You can chain refinements together, since that returns another QuerySet.
Lets say the model is User, and the field is name.
User.objects.filter(authuser=request.user) \
.only('name')
You can pass other fields to .only(), they just need to be comma separated.

Related

Group list items by field value in the Django admin

I'm trying to group the items in the Django admin app by a specific field (e.g. date).
So I've added to the queryset in admin.ModelAdmin.getQueryset() the following:
queryset = queryset.values('date').annotate(Sum('amount'))
But this doesn't work because in this case, a dict is returned instead of a queryset.
I started exploring what's inside the django/contrib/admin folder, and I think something need to be done before sending the object to the template change_list.html.
I'm not sure but I think the class in views/main.py (admin folder) might need some change.
Can anybody confirm that what I'm trying to do is achievable at all?
Please find below a representation of what I'm trying to achieve:
Follow the below example in URL. it's has great way to understand with override django admin with custom queryset and groupby data
https://medium.com/#hakibenita/how-to-turn-django-admin-into-a-lightweight-dashboard-a0e0bbf609ad
I found this useful: https://github.com/xacce/django_admin_grouper
You can simply define the group in ClassAdmin
class RecordAdmin(admin.ModelAdmin):
def regroup_by(self):
return 'category'
The repo overrides Django's change_list_results.html. If your RecordAdmin has method reggroup_by than it inserts a row with the name of the category. If reggroup_by is missing it works as usual.

What is the best approach to design model fields that is like a list in Django?

Let's say I have a model called 'SysApp'. Each system has 5 documents. Each document has fields:
Title
URL to the file (external url)
Description
Rather than defining multiple fields like
title_1,
url_1,
description_1,
title_2,
url_2,
description_2
(Hardcoded approach)
is there a better way to handle this type of use case?
One way of doing is to create a model storing each document and then SysApp will reference each document using a ForeignKey. However I still have to create field like document_1, document_2 etc. Also it would be quite difficult for editors to manage when there are 100+ SysApp and 3-400+ documents.
Is it possible to manage these fields like a list or dictionary?
Thank you
I think the best way to organize your 'SysApp - documents' relationship, assuming that each document is related to only one sysapp, is to use ForeignKey, as you mentioned.
In that case you'll only have to create 2 models: the first one is SysApp with a name field and the second is Document with fields title, url to file, description and a foreignkey to SysApp. Now you can create documents and attach them to the sys you want. So you do not need to specify document_2, document_3 etc. fields.
If you need to attach one document to more than one sysapp use ManyToMany instead of ForeignKey.

Making an alias for an attribute field, to be used in a django queryset

In Django, how does one give an attribute field name an alias that can be used to manipulate a queryset?
Background: I have a queryset where the underlying model has an auto-generating time field called "submitted_on". I want to use an alias for this time field (i.e. "date"). Why? Because I will concatenate this queryset with another one (with the same underlying model), and then order_by('-date'). Needless to say, this latter qset already has a 'date' attribute (attached via annotate()).
How do I make a 'date' alias for the former queryset? Currently, I'm doing something I feel is an inefficient hack: qset1 = qset1.annotate(date=Max('submitted_on'))
I'm using Django 1.5 and Python 2.7.
Even if you could do this, it wouldn't help solve your ultimate problem. You can't use order_by on concatenated querysets from different models; that can't possibly work, since it is a request for the database to do an ORDER BY on the query.
It seems qset1 = qset1.annotate(date=Max('submitted_on')) is the closest I have right now. This, or using exclude(). I'll update if I get a better solution. Of course other experts from SO are welcome to chime in with their own answers.

Django Rest Frame API: additional fields in ModelSerializer

Can I add additional fields to ModelSerializer subclass?
By saying 'additional field', I mean some fields don't belong any models in database, which any effort that try to map those fields to exist model fields will fail. The reason I need to include those fields is for design purpose. I need to those fields' value to do the validation and creating a new instance eventually.
I know there is a kwarg in ModelSerialzer called 'context'. By putting all the additional information into 'context', it will work. However, I want to know is that possible to create additional fields?
I have tried adding 'write_only=True', which doesn't work. The only left option is to override default restore_object method to create the instance with my will.
Any other ideas?
As you have not posted any code I can only give you a generic answer, but if I understand you correctly, you wish to add a custom field to a ModelSerializer thats not part of your model...
In DSF you can do this very esaily (read here):
In this case you just want a simple read-only field, so instead just use:
custom_field = Field(source='get_whatever')
In terms if validation after that please read the DRF guide here

Django: Overriding verbose_name for AutoField without dropping the model

I am using 0.97-pre-SVN-unknown release of Django.
I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.
Hmm... and what about explicitly write id field in the model definition? Like this for example:
class Entry(models.Model):
id = models.AutoField(verbose_name="custom name")
# and other fields...
It doesn't require any underlying database changes.
Look into the command-line options for manage.py; there's a command to dump all of the model data to JSON, and another command to load it back in from JSON. You can export all of your model data, add your new field to the model, then import your data back in. Just make sure that you set the db_column option to 'id' so you don't break your existing data.
Edit: Specifically, you want the commands dumpdata and loaddata.

Categories

Resources