get the list of slugs of particular attribute instance

  fastapi, python, python-3.x, sqlalchemy

I need a list of slugs of a particular attribute instance. I wanted the functionality of django’s values_list in sqlalchemy so I did the following

async def check_values_are_unique(db, attribute_value, attribute):
    # get the list of slugs of particular attribute.
    # alternative of django values_list in sqlalchemy
    existing_values = await db.execute(select(attribute.values.slug).distinct()).all()
    for value_data in attribute_value:
        slug = slugify(value_data.title)
        if slug in existing_values:
            msg = "Value %s already exists within this attribute." % value_data["name"]
            # raise validaton error
            raise HTTPException(
                status_code=404,
                detail=msg,
            )

    new_slugs = [slugify(value_data.title) for value_data in attribute_value]
    if len(set(new_slugs)) != len(new_slugs):
        raise HTTPException(
            status_code=404,
            detail="Provided values are not unique.",
        )

data is in the following format:

AttributeCreateInput(title=’Material’, slug=’material’,
values=[AttributeValueCreateInput(title=’Cotton’, value=’cotton’)],
value_required=True)

values_input = data.values
attribute_input = data.__dict__
del attribute_input["values"]
attribute = Attribute(**attribute_input)
for val in values_input:
    attribute_value = AttributeValue(**val.__dict__, attribute=attribute)
await check_values_are_unique(db, values_input, attribute)

This way I am getting "'InstrumentedList' object has no attribute 'slug'", error. Why am I getting such issue and how can I get the list of slugs like in django (attribute.values.values_list("slug", flat=True)) ?

Source: Python-3x Questions

LEAVE A COMMENT