Django - Delete particular field data from model - django

I am trying to delete a field's data from Django model. Suppose I have a model named UserData and I want to delete city field for record_Id = 1, without deleting the data from other fields for record_Id = 1. I used:
UserData.objects.filter(city="London").delete()
but it deletes the whole record. I tried this method on SO, but gives attribute error Delete field from standard Django model .
Let me know how to do this. Thanks!

When you want to delete the value of specific field in a row, then it is termed as updating the field's content to null value and not deleting the field. In this case, if you want to update the field's value to null, use following statement.
UserData.objects.filter(record_Id=1).update(city=None)

Related

django view filter ManyToMany field to guard view

I have a tag model, with ManyToMany field "parents" to tag model, to itself. There is also "allowed_users" field.
I need to guard a view in such a way, that the user won't see any tags in parents field, to which he is not allowed.
I try to modify queryset, removing the corresponding tags from parents. But when I change the instance, tag_instance.parents.set(my_new_list) it gets saved automatically so I'm altering the database and changing the real value of the instance.
So the general question is "how to guard my view in such a way, that object's ManyToMany field is filtered by custom logic".
Another question is "how to set manytomany field without altering database", as this would be a solution to the former one.
yes I use DRF
You can use the Prefetch object to filter related table when SQL queries are executed.
For instance:
Tag.objects.preftech_related(Prefetch("parents", queryset=Tag.objects.filter(allowed_users=current_user).distinct()))
This will prefetch "parents" (meaning no additionnal sql query will run when accessing my_tag.parent.all()) and filter parents to keep only those with the current user in allowed_user
Note: Tag.objects.filter(allowed_users=current_user) will duplicate tag entries for each user in allowed_user, ence the .distinct() to keep one of each

How do i get the highest ID of an item within a database in djngo?

When I try to save a new item I need to find the item with the highest ID in the database in order to add 1 to it and save the next item in the order in the database. Simply counting the items in the DB will not work as if an item is deleted the count will be incorrect.
I have no code to fix but pseudo looks something like:
look at all the items in the DB
Find the item with the highest ID
Add one to that number
save the new item with the new highest id in the DB
I am using Django. as such it should use the querysets within Django and or python.
Field id of the Django Model is by default auto increment so whenever you save a new object to the database it does exactly what you want - saves object with id greater than the last object's id by one.
Anyways, there are multiple ways you can retrieve latest id from the database.
The most efficient way (simplest and fastest database query since you want only id value returned, not the whole object) is by saying:
latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first()
The queryset looks like this:
SELECT 'model'.'id' FROM 'model' ORDER BY 'model'.'id' DESC LIMIT 1;
all() gets all objects of the model from the database, values_list('id', flat=True) extracts only the value of the id field (this saves you time because you don't retrieve all model fields), order_by('-id') orders objects by id in descending order and first() gives you the desired result which is the last id.
There is also method like last() that does the oposite of method first(). It retrieves last whole object of the model from the database or the method latest('id') which does the same.

Change primary key on manytomany field Django

Is it possible to change primary key of many to many field from default to uuid?
Table is already populated. What is the best way for migration?
You can create a migration that executes raw queries, add a new field to the table in the middle then generate the new UUID.
After that, another set of queries to drop the constraints on ID, add the new constraints to the new UUID field, and lastly drop the old ID field.
https://docs.djangoproject.com/en/2.0/ref/migration-operations/#runsql

How can I get the object value of a combobox in django view?

I am creating an app in django and to do that I have a form where the field 'Person' is a ForeignKey field. So, when I run the application it appears a form correctly showing me a combobox that lets me select the 'Person' object that I want. But the problem is when I try to catch the information in the view.
I send data with a POST method, so, when I try to get the value of the selected 'Person' object in the view I do the next:
selected_person = request.POST['person']
(Person is the field name)
I was surprised when I tested that the value of the variable 'selected_person' is a number (concretely, the number of the selected index of the element in the combobox).
My question is: HOW CAN I GET THE OBJECT VALUE OF THE SELECTED ELEMENT IN THE COMBOBOX?
Than you so much!
No, it is the primary key of the Person object in the database. So you can get it via Person.objects.get(pk=selected_person).
But really you should be using a Django form, which will then give you the Person object via form.cleaned_data['person'].
Also note, for clarity, this is a select field, or a drop-down, not a combobox; a combobox is a desktop widget that has both a drop-down and an edit field.
Concretely, the problem was I didn't have defined a "primary_key" value in the model, so, the number that the drop-down list gives me is the default primary key that django attached to the model. If I define a customized primary key for the model, the selection of the element in the drop-down list gives me the primary key.

Django Autoselect Foreign Key Value

I have a model that contains a foreign key value, then in the form generated from this model, I want to auto select the record's key according to the record I'm adding the form's contents to...I've tried the below code, but it tells me QuerySet doesn't contain vehicle
stock = Issues.objects.filter(vehicle=id)
form = IssuesForm(initial={'id_vehicle': stock.vehicle})
I'm a bit new to django btw so any ideas are highly appreciated
filter always gives a QuerySet, which is a set of values. If you just want a single object, you should use get.
However I don't really understand why you need to do the lookup at all. You have the id value already, since you are using it to look up stock. So why don't you just pass id as the value for id_vehicle?