0

I have a PSQL database with portfolios and their values each day for a few years. I'm using Django to develop a web app behind this. I used this link: https://docs.djangoproject.com/en/1.10/howto/legacy-databases/

to generate the models for Django. I did not explicitly define a primary key in my database or in the models.py file. Is it necessary to define a primary key in order to retrieve data from the DB?

If so, is there a way to make multiple fields a primary key? In this case it has to be the portfolio ID and the date, since there are multiple portfolios and dates.

Thanks for any help!

user3628240
  • 877
  • 1
  • 23
  • 41

4 Answers4

4

It is not necessary to define primary key in your code. By default it is taken care by django. It creates variable called id as Primary key.

However you can explicitly define primary key by using primary_key = True option.

Example.

    key1 = models.IntegerField(primary_key=True)

If you want to define composite primary key then you can have a look at this question How to create composite primary key

Hope this helps !

Community
  • 1
  • 1
Jay Parikh
  • 2,419
  • 17
  • 13
2

By default, django created a column called id for each table, which is the PK.

You can use your own PK using primary_key=True.

Also, you can use unique_together Meta option, but you still need to use another column as PK.

If what you want is to use composite primary key, you need to use another thirdparty solution.

afilardo
  • 527
  • 2
  • 16
1

I faced the same issue and it was solved by replacing IntegerField by AutoField as below,

order_id = models.IntegerField(primary_key=True)

by

order_id = models.AutoField(primary_key=True)

And it worked !!

Nurhun
  • 475
  • 1
  • 9
  • 21
0

PostgreSQL dont make auto pk field. so you need to make it manually.

models.py

test = models.AutoField(primary_key=True)

you dont need unique=True, because pk is always unique or you can use this, to generate a auto pk field

settings.py

DEFAULT_AUTO_FIELD='django.db.models.AutoField'
Gin
  • 11
  • 3