简体   繁体   中英

Python - in operator and getitem

I would like to get an item from a list of objects if a key value is in that list. I am using Django.

attributesValues = AttributeValue.objects.filter(feature__pk = feature_id)
for key, value in request.POST.iteritems():
    if key in attributesValues.attribute.name:
            ## here i'd like to get the matching item and name it attributeValue and give it a new value
            attributeValue.value = value
            attributeValue.save()
    else:
            #here the key is not in the list attributesValues so I'll create a new object
return HttpResponse("")

You can do something like this :

if request.method == "POST":
    post_dict = request.POST.copy()
    keys = post_dict.keys()
    attributesValues = AttributeValue.objects.filter(feature__pk = feature_id, 
                                                     attribute__name__in=keys)

    for av in attributesValues: #update all the records that are present
        if av.attribute.name in keys:
            av.value = post_dict.get(av.attribute.name)
            if av.value:
                av.save()

    #Now fetch all the new keys can create objects. 
    avs = attributesValues.values_list('attribute__name', flat=True)
    new_keys = list(set(keys) - set(list(avs)))
    for key in new_keys:
        av = AttributeValue.objects.create(feature_pk=feature_id, 
                                           value = post_dict.get(key))
    #rest of the code. 

what about something like this?

attributesValues = AttributeValue.objects.filter(feature__pk = feature_id)
for key, value in request.POST.iteritems():
    if attributesValues.filter(attribute__name = key).exists():
            attributeValue = attributesValues.get(attribute__name = key)
            attributeValue.value = value
            attributeValue.save()
    else:
        # create a new object
return HttpResponse("")

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