Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the primary key id that is auto generated in Django Models

I have a DB Schema that I have inherited from some legacy code. Now we intend to use Django to reflect the tables into models. This means I cannot have the tables be generated using the django models. The table schema looks like so:-

mysql> desc student_profile;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| joining_on  | datetime    | YES  |     | NULL    |                |
| brothername | varchar(45) | YES  |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

Now the Django model that I have created for this schema looks like this:-

class StudentProfile(models.Model):
    id=models.IntegerField(primary_key=True)
    joining_on=models.DateField()
    brothername=models.CharField(max_length=45)

    class Meta:
        db_table="student_profile"

When I insert a row into this, like so:-

StudentProfile.objects.insert(brothername="Bro")

The row is correctly inserted. But I do not have a way to extract the id field. It appears that since this field is not an AutoField, django does not copy over the id that was automatically generated by MySql. What can I do to obtain the id value with which the row was created? I checked (https://code.djangoproject.com/ticket/8799#comment:1), and this appears to be by design. But I still need a way to get to the id and have it be reflected in the StudentProfile model. What can I do?

One solution could be to override the default save() and explicitly provide the id into the save() of the model. But is that the right way? The database (it is MySql) provides a way to generate the id, and I must be able to use this fact to my advantage rather than having to maintain a running counter by the application. Any hints?

like image 748
abhayAndPoorvisDad Avatar asked Mar 03 '16 10:03

abhayAndPoorvisDad


1 Answers

You can skip defining the id column altogether, ie:

class StudentProfile(models.Model):
    # id=models.IntegerField(primary_key=True)
    joining_on=models.DateField()
    brothername=models.CharField(max_length=45)

    class Meta:
        db_table="student_profile"

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

If the column name was different, you could use an AutoField with a different name, such as:

my_id = models.AutoField(primary_key=True)
like image 83
Selcuk Avatar answered Oct 17 '22 12:10

Selcuk