0

如果键值在该列表中,我想从对象列表中获取一个项目。我正在使用 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("")
4

2 回答 2

2

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. 
于 2013-09-26T14:35:32.263 回答
0

像这样的东西呢?

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("")
于 2013-09-26T14:54:12.617 回答