简体   繁体   中英

Filter data from models based on some condition

I have two models Clients and clientData related with foreign key. I want to select all those clients which are not in clientData model.The structure of models are as follows :

class Client(Model):
    name = CharField(max_length=NAME_FIELD_LENGTH)
    nickname = CharField(max_length=NAME_FIELD_LENGTH, null=True, blank=True, db_index=True)


class clientData(Model):
    art = ForeignKey(Art)
    client =  ForeignKey(Client)
    pj = ForeignKey(Pj, null=True, blank=True)

If I run this query

val = Client.objects.filter(clientswiki__client = 1)

It return me the value of client whose id is 1 and it should be but what I want is if clientData has only one entry which is client id 1 then it will return all other entries from Client model expect id 1 and I don't how to get that.

To select the clients that aren't present in clientData, we can get a list of clients across the clientData records and then run an exclude to filter them out.

included_clients = clientData.objects.values_list('client', flat=True)

excluded_clients = Client.objects.exclude(id__in=included_clients)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM