0

I want to access primary key, so that the admin can change the primary key to whatever they want.

class TheDataBase(database.Model):
    id = database.Column(database.Integer, primary_key=True, autoincrement=True)
    name = database.Column(database.String(20), nullable=False)
    descrip = database.Column(database.Text, default="N/A")

I have tried adding a column like this but this gives error

name_id = database.Column(database.Integer, default=id)

is anyway to do something similar to this? I don't want to define another database if its possible. I hope I made my question clear

Arya Kurdo
  • 47
  • 5
  • Allowing people to change primary keys may cause problems if, for example, the key is used to define foreign key relationships with other tables. Why would the admin need to change the primary key? – snakecharmerb Jun 30 '20 at 11:01
  • See this [this answer](https://stackoverflow.com/a/9985219/5320906) for why postgresql doesn't reuse deleted ids. Your particular database may or may not suffer from similar limitations. – snakecharmerb Jun 30 '20 at 13:04
  • Really appreciated buddy thanks for the help, Ok then is there anyway I can put for example the third object in a database to another database or lets say some objects with particular names I want to have them in another database – Arya Kurdo Jun 30 '20 at 13:17

1 Answers1

0

Ususally change the primary key of a table is really bad. It should be done just if the table design is wrong. What I can suggest you is to use a couple of alternatives. You can, for example, define a unique constraint that the user is able to change. Onestly I don't like also this solution. Another thing you can think about is to design a sort of help table with the constraints you need then apply a foreign key with the main one.

By the way. What is the purpose of the script? Maybe if you can give us a use case we can found a better solution.

bull90
  • 689
  • 5
  • 12
  • Its a movie database I want an Id for every movie the Id should be changed if the admin wants to, so that if he deletes 5 in between lets say 4 and 6 then he can add another movie with the id of 5 the normal id(primary key) doesnt allow this – Arya Kurdo Jun 30 '20 at 12:52
  • Let me say, what do you want to change is not the primary key,but it is instead a business key. A primary key is not useful for the user. As I told you before,you can simply create a business key with a UQ constraint, let the user change it and let the system use any id it prefers. You can create a custom function and fill the field with the missing value so that it can be incremental. Please refers to https://docs.sqlalchemy.org/en/13/core/constraints.html#unique-constraint and https://docs.sqlalchemy.org/en/13/core/defaults.html#python-executed-functions – bull90 Jul 01 '20 at 13:26