closeio / flask-common

Some commonly shared code for Flask, MongoEngine, and Python apps
26 stars 4 forks source link

Pregenerate PK #37

Closed tsx closed 6 years ago

tsx commented 7 years ago

Make PK available before saving object.

tsx commented 7 years ago

Using this increases chances of accidentally creating inconsistency.

tsx commented 6 years ago

@jtharpla would like to use an ID for saving data to S3 before creating corresponding objects in mongo.

thomasst commented 6 years ago

What's the exact use case? Note that we want to move to shorter IDs (UUIDs) for any new collection. The new IDField already supports this behavior with the autogenerate=True option.

https://github.com/closeio/flask-common/blob/master/flask_common/fields/id.py

wojcikstefan commented 6 years ago

Just to make the behavior of the IDField more obvious, here's how it can be used in the wild:

In [4]: class TestDoc(Document):
   ...:     id = IDField(autogenerate=True, prefix='test', primary_key=True)
   ...:     name = StringField()
   ...:

In [5]: TestDoc.objects.create(name='aaa')
Out[5]: <TestDoc: TestDoc object>

In [6]: TestDoc.objects.create(name='bbb')
Out[6]: <TestDoc: TestDoc object>

In [7]: [t.pk for t in TestDoc.objects]
Out[7]: ['test_0Q9FASnMdGR4cVGtbJeRZG', 'test_6S2aaGjfjfefaCPePdroZB']

In [8]: new = TestDoc()

In [9]: new.pk
Out[9]: 'test_0hNrWgYDJ0HqyUdssV92SX'

That last line shows how you can access the PK before you save the document.

jtharpla commented 6 years ago

I ended up coding my stuff a different way where I didn't need to pre-generate the ID

thomasst commented 6 years ago

Let's just reopen if we need this again.

thomasst commented 6 years ago

@tsx Reason for reopen?

tsx commented 6 years ago

I'm thinking I might need it for fixing 10510 in the main repo.

While I see now we have IDField that works better, I can't easily migrate existing documents that use the old RandomPKDocument.

Still digging though...