I am using a SQL database. I don’t have any control over this database, but there are some tables I need data from. I wanted to create a model in Django for said table, but it uses a unique index instead of a primary key. Is there any good way to create this model. I’m open to any solutions.
I was able to verify my connection to the db and pull data for any table that has a primary key.
my table models are set up to look something like this.
Can you clarify a bit? It’s hard to understad what you are trying to do and where you’re facing the challenge.
You said that you have no control over the database, but you want to read data from it. But with Meta.managed = True you declare the opposite.
You also said that the table has no primary key, but you explicitly define one on column1.
What do you mean by “unique index”? You can have a unique constraint, without creating an index for it. Indexing is done for performance reasons and is completely transparent when reading or writing to the database.
Maybe it would also help if you would include the layout of the original data?
@Mas - As long as you are using this model as a read-only data reference, you can select any arbitrary column and assign it as if it were the “primary key” - Django isn’t going to care. However, if you are going to be trying to update this model using Django, you really need to have a single-column primary key.
And yes, as mentioned above, if you don’t have any control over the table, you absolutely want it to be managed = False.
I can read/update the db, I can’t change the structure of the db.
the example shown was for the tables that do have primary keys.
By unique index, I mean whoever created the table, made it with no unique columns. the only way to get something unique is using multiple columns together. Im not super familiar with databases, I called it a unique index. see image below
If you have anyone column that is unique within the table, then you can use that column as if it were the primary key.
If your only unique indexes are on multiple columns, then you’re stuck. Do not try to update those tables using the Django ORM. (You could still update them using raw SQL.)
No. The Django ORM requires a single-column primary key for how it manages objects internally. It’s also required for any models having a foreign key relationship with that model.