Can I delete an item of a queryset in python but without deleting that item on the database?

5.2k views Asked by At

I am creating an app in django, and I have the next problem:

I get a queryset using the next command line:

queryset = Persons.objects.all()

Assume the resulting list is the next one: ['x', 'y', 'z']

And I want to remove an element x of that list, so that the resulting list is: ['y', 'z'].

I don't want to delete the element x. So I cant 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 a queryset of B objects that are related with A and A.att2 value == 'test' ???

3

There are 3 answers

2
Ben Hsieh On BEST ANSWER

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)

query like this:

B.objects.filter(A_model__att2="test")

this is my first Answer in stackoverflow hope this will help you

if you don't want to set related_name try:

B.A_set.filter(att2="test")
1
Paco On

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, such as:

class Item(models.Model):
    user = models.ForeignKey('User')
    value = models.CharField(max_length=128)

You can exclude some items where the user has the 'admin' username. You can use the exclude function.

Item.objects.exclude(user__username='admin')
0
Ben Hsieh On

Or you can create another field

in model something like :

class Persons(model.Models):
    name = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

give x a value of "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)