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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With