Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Sequences as Default Value for Django Model Field

I have a PostgreSQL database that is being used by a front-end application built with Django, but being populated by a scraping tool in Node.js. I have made a sequence that I want to use across two different tables/entities, which can be accessed by a function (nexval(serial)) and is called on every insert. This is not the primary key for these tables, but simply a way to maintain order through some metadata. Using it in Node.js during the insertion of the data into the tables is trivial, as I am using raw SQL queries. However, I am struggling with how to represent this using Django models. There does not seem to be any way to associate this Postgres function with a model's field.

Question: Is there a way to use a Postgres function as the default value of a Django model field?

like image 330
P Ackerman Avatar asked Oct 16 '25 03:10

P Ackerman


1 Answers

you can also set your own function for the default

from django.db import connection, models

def sequence_id():
  with connection.cursor() as cursor:
    cursor.execute("""SELECT nextval('model_someid_seq')""")
    return cursor.fetchone()[0]


class MyModel(models.Model):
  field_id = models.IntegerField(default=sequence_id)
like image 80
MrE Avatar answered Oct 18 '25 17:10

MrE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!