So, I want to import a file and generate a unique ID for each field during the import process. Is that possible? And if it’s possible. Where should I do this? Aside making sequential in my corresponding module.
It is possible but you should not do anything to get it. The tryton framework does it automatically for you.
You just need to import the records. Once imported you can export the same record again. Make sure to include the ID
field in the export which is the unique id generated by tryton.
Ah, no. I think this module make their own unique id.
@classmethod
def generate_puid(cls):
STRSIZE = 8
puid = ''
for x in range(STRSIZE):
if (x < 3 or x > 5):
puid = puid + random.choice(string.ascii_uppercase)
else:
puid = puid + random.choice(string.digits)
return puid
I had to adjust this to my company policy. So, yeah…
It might look like it will generate unique ids but this code is using randomness to generate the ids and if you’re not lucky two ids might collide.
It can work for your use case, but I would be wary of trusting all the ids to be unique.
You should use an Unique
constraint so that you can rely on it.
Ah, yes I am aware. I’ve changed it to a better sequence that will not have any redudancy. The thing is I have 900 records I suppose to insert to tryton. but i don’t know how to generate it if i have to import it.
You can look how it is done in ir.session
create method.
Can you elaborate, I am sorry I don’t understand.
He means that there is an example on how to achieve what you want to do in the create method of ir.session model.
I copy here the relevant functions:
@classmethod
def default_key(cls, nbytes=None):
return token_hex(nbytes)
@classmethod
def create(cls, vlist):
vlist = [v.copy() for v in vlist]
for values in vlist:
# Ensure to get a different key for each record
# default methods are called only once
values.setdefault('key', cls.default_key())
return super().create(vlist)
Here is a brief explanation of what does each function:
default_key
: Generates a secure random hexadecimal string, potentially used as a unique identifier for a record.create
: Customizes the record creation process by ensuring that each record gets a unique key (usingdefault_key
) if one is not provided in the input data. Then, it proceeds to create the records via the parent class’screate
method.
Ah, so if I import them through tryton I should write that in my module?
Yes, you should write that on your module, activate it on the database and then the server will execute the custom code to generate the unique id whenever a new record is created (thanks to the fact that you overrided the create
function)
Ah, okay, thank you, I understand.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.