Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset exclude values

models.py

class ChatMessage(models.Model):
    ip=models.IPAddressField()
    message=models.CharField(max_length=200)

class BlockIp(models.Model):
    ip=models.IPAddressField()

admin.py

class ChatMessageAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(ChatMessageAdmin, self).queryset(request)
        #block=BlockIp.objects.all()
        return qs.exclude(ip='1.1.1.1')

I have rewrite the queryset method for ChatMessage class. I am trying to return something like:

SELECT * FROM chatmessage as v1 JOIN blockip as v2 on v1.ip!=v2.ip

so the user see only the messages which have an ip which is not in a blockip entry

return qs.exclude(ip=BlockIp.objects.all().ip) is not syntax correct :(

Any advice?

like image 253
Chris P Avatar asked Dec 08 '22 16:12

Chris P


1 Answers

Django provides some operators that you can use when filtering values. In particular, you want the __in operator. You could do something like this:

blocked = BlockIp.objects.all().values_list('ip', flat=True)
messages = ChatMessage.objects.exclude(ip__in=blocked)

values_list will return the given values (in this case, just the ip field) as a list.

like image 111
mipadi Avatar answered Dec 11 '22 09:12

mipadi