Is it possible to delete a query item in python, but without deleting that item in the database?
I am creating an application in django and I have the following problem:
I am getting queryset
with the following command line:
queryset = Persons.objects.all()
Suppose the following list is as follows: ['x', 'y', 'z']
And I want to remove an item x
in this list to get a list: ['y', 'z']
.
I don't want to delete an item x
. Therefore, I cannot use the command item.delete()
.
If my models are:
class A(models.Model):
att1= models.ForeignKey(B)
att2 = models.CharField(max_length=128)
...
class B(models.Model):
ident = models.CharField(max_length=128)
...
How can I get the queryset of B objects related to the values of A and A.att2 == 'test' ???
source to share
I think you need to set related_name:
class A(models.Model):
att1= models.ForeignKey(B, related_name='A_model')
att2 = models.CharField(max_length=128)
class B(models.Model):
ident = models.CharField(max_length=128)
run the following queries:
B.objects.filter(A_model__att2="test")
this is my first answer on stackoverflow, hope this helps you
if you don't want to set the associated try name:
B.A_set.filter(att2="test")
source to share
For example:
# we usually don't import User directly
# but I just wanted to show how to use exclude
from django.contrib.auth import User
User.objects.all() # will return all users
# will return exxactly the same queryset
# except that the user with the `admin` username
# will be excluded from the queryset.
User.objects.all().exclude(username='admin')
If you have some related fields like:
class Item(models.Model):
user = models.ForeignKey('User')
value = models.CharField(max_length=128)
You can exclude some items where the user has the username "admin". You can use exclude function .
Item.objects.exclude(user__username='admin')
source to share
Or you can create another field
in the model something like:
class Persons(model.Models):
name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
set x to "is_active" = False
x1 = Persons.objects.get(name='x')
x1.is_active = False
x1.save()
now you can filter like this:
queryset = Persons.objects.filter(is_active=True)
source to share