V
V
Vitaly2015-09-29 13:08:54
Django
Vitaly, 2015-09-29 13:08:54

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:
        ...

Also a related question!
In the models I added for output:
def __unicode__(self):
return self.ip # IP output
How do I put this value into a variable?
those.
object = object.get(pk=1)
temp = object.ip

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2015-09-29
@NeiroNx

test_ip = set_like[0].ip
So?

O
Oscar Django, 2015-09-29
@winordie

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?

D
Dmitry Astrikov, 2015-10-01
@astrikovd

Use the first() method instead of what you wrote.

like = Like.objects.filter(ip=client_ip).first()  # Вытаскиваете первый объект из полученного кверисета.
if like:
     test_ip = like.ip
     ...

PS Avoid using keywords as variable names (in your example, don't use the word object)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question