4

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?

1

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

If i do this the sequence runs many times. Easy 30 times. I use your function "sequence_id()" in admin.py overriding save_model
1

My eventual solution:

Override the save method of the model, using a raw query to SELECT nextval('serial') inside the override, setting that as the value of the necessary field, then call save on the parent (super(PARENT, self).save()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.