Answer the question
In order to leave comments, you need to log in
How to access the fields of an object without using for?
Hello, I want to access a field of an object. Of course, I do it through a FOR loop, but I'm sure! know i am only getting one object, how can i shorten the code?
try:
set_like = Like.objects.filter(ip=client_ip)[:1] # Это фильтр и получение одного объекта
except ObjectDoesNotExist:
...
else: # Это то что планирую сократить
for t_ip in set_like:
test_ip = t_ip.ip
if client_ip in test_ip:
...
else:
...
Answer the question
In order to leave comments, you need to log in
Like.objects.filter(ip=client_ip).first()
Although it's not really clear what the filter is for, use get if there's only one element.
Like.objects.get(ip=client_ip)
If there are several objects, are you sure that the right one will be the first one?
Use the first() method instead of what you wrote.
like = Like.objects.filter(ip=client_ip).first() # Вытаскиваете первый объект из полученного кверисета.
if like:
test_ip = like.ip
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question