PynamoDB icon indicating copy to clipboard operation
PynamoDB copied to clipboard

custom name for map attributes

Open Seluj78 opened this issue 4 years ago • 3 comments

Hi,

I'm currently a bit stuck. I have to create a model of our dynamodb using pynamodb, and here's what I have (part of a bigger model, exported from a real user in DB)

packs = [
  {
   "exos": {
    "4": {
     "start": 1529411739,
     "session": 1529411739,
     "finish": 1529417144
    },
    "5": {
     "start": 1529417192,
     "session": 1529417192
    }
   },
   "id": 10
  },
  {
   "exos": {
    "32": {
     "start": 1529411706,
     "session": 1529411706
    }
   },
   "id": 17
  }
 ]

Here's what I got so far:

class ExercisesMapAttribute(MapAttribute):
    pass


class PackMapAttribute(MapAttribute):
    exos = ExercisesMapAttribute()
    id = NumberAttribute()


class TrainUser(Model):
    class Meta:
        table_name = 'TrainUser'
        region = 'eu-west-1'
    # [...] Other stuff removed for clarity
    packs = ListAttribute(of=PackMapAttribute())

Currently I think I got correctly up until the "4":, "5": etc... As they are exercices name. The idea is that this structure is supposed to represent a list of packs, then inside a list of exercises with their id and more info... I need a way to map that from the current db json to classes I can then use with PynamoDB. Is it even possible?

Thanks!

Seluj78 avatar Dec 21 '21 16:12 Seluj78

Or another solution would be to generate the models from the db but I am not sure such script exists

Seluj78 avatar Dec 22 '21 11:12 Seluj78

I can't get DynamicMapAttribute to work, so I'm wondering if my only option is to do a custom attribute

Seluj78 avatar Dec 22 '21 14:12 Seluj78

Unfortunately the current implementations of MapAttribute and DynamicMapAttribute don't allow you to model the values when keys are dynamic. Your options would be to either have pynamodb remain ignorant to what's in exos (i.e. exos = MapAttribute()) or to write a custom attribute that allows you to do something like exos = MapAttribute(of=ExerciseMapAttribute) which knows how to serialize/deserialize with dynamic keys

garrettheel avatar Jan 03 '22 22:01 garrettheel

Closing because I won't personally have the need anymore since we're moving to a relational database and using peewee.

Seluj78 avatar Mar 28 '23 21:03 Seluj78