Skip to content

PynamoDB's Model.get operation throws an incorrect exception when getting an object with only single optional attribute_to_get #1287

@domderen

Description

@domderen

Hey,

I just ran into an issue while using Model.get API. I called it with a single attribute value in attributes_to_get parameter. This attribute in my model is an optional value, that might not exist on my DynamoDB object. So when the underlying get_item call is made, it returns a response where Item field is an empty dict ({}).

So then this if case is executed, which evaulates to false, and because of that, a DoesNotExist exception is thrown.

I would expect this API to return an empty object, or at least throw a different kind of exception. Though in my case, such a query is completely valid, so I would prefer an empty object response. I worked around it by requesting the attributes_to_get parameter with two values, my hash key attribute, and my optional attribute. That way I always get some value to deserialize into class instance.

What do you think? Do you think this is something that should be modified in PynamoDB?

A small sample to present what I mean

from pynamodb.attributes import (
    UnicodeAttribute,
)
from pynamodb.models import Model


class SomeModel(Model):

    id = UnicodeAttribute(hash_key=True)
    optional_attr = UnicodeAttribute(null=True, default=None)

def get_optional_attr():
    try:
        # this throws an exception even if instance with hash_key 1 exists, but it doesn't contain a value for optional_attr.
        return SomeModel.get("1", attr_name=["optional_attr"]).optional_attr
    except Exception as e:
        print(e)
        return None

def get_optional_attr_with_default():
    # This works fine, returning a None for optional_attr, but it also obtains the "id" attribute from DynamoDB.
    return SomeModel.get("1", attr_name=["id", "optional_attr"]).optional_attr

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions