Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8060053
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T09:51:48+00:00 2026-06-05T09:51:48+00:00

What methods do you use to set up database level defaults in django? I

  • 0

What methods do you use to set up database level defaults in django?

I understand this is a django wontfix decision, but there must be some ideas floating around about a way to implement this if written for a specific backend (postgres).

I’d like to power this through python so I’d prefer not to use /sql/.sql files.

I was thinking I might set attributes on existing fields such as:

foo = models.CharField(max_length=256, blank=True)
foo.db_default = ''

Then filter through fields and construct an ALTER COLUMN SET DEFAULT query.

Where would I put that though? The docs say not to alter the database in the post_syncdb hook.

Any ideas where to put this action? I’m also thinking I could generate the sql/.sql files dynamically. A management command would be better than nothing. Automatic would be great. Hmm I wonder if post_syncdb can generate sql files in time to be executed? Will test.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T09:51:50+00:00Added an answer on June 5, 2026 at 9:51 am

    I tried doing post_syncdb but it was too late to use .sql files. Hooking into class_prepared worked out in time for syncdb but I realized I was overcomplicating things. I might as well run some code once at model instantiation.

    I ended up with a straight forward solution that can be easily understood in 6 months when I need to fiddle with this again.

    def db_default(field, db_default):
        """
        Set attribute __db_default for signal to set default values with.
        """
        field.__db_default = db_default
        return field
    
    class OrderShipLog(models.Model):
        date = db_default(models.DateTimeField(), 'now()')
    
    def generate_default_sql(model):
        """
        Generate SQL for postgresql_psycopg2 default values because the shipping
        database post doesn't guarantee posting certain fields but id like them all to be strings.
        """
        db_fields = filter(lambda x: hasattr(x, '__db_default'), model._meta.fields)
        db_table = model._meta.db_table
        modelname = model._meta.object_name
    
        sql_dir = os.path.join(os.path.dirname(__file__), 'sql/')
        sql_filename = os.path.join(sql_dir, '{modelname}.postgresql_psycopg2.sql'.format(
            modelname=modelname.lower()))
    
        from django.db import connection
        if not db_table in connection.introspection.table_names():
            print >> sys.stderr, "{0} not in introspected table list; creating db default sql file : {1}".format(db_table, sql_filename)
            try:
                if not os.path.exists(sql_dir):
                    os.makedirs(sql_dir)
    
                with open(sql_filename, 'w+') as f:
                    for field in db_fields:
                        attname, db_column = field.get_attname_column()
                        if not field.__db_default:
                            raise Exception("Must enter value for field {modelname}.{field}.__db_default".format(
                                modelname=modelname,
                                field=attname))
                        f.write('ALTER TABLE {db_table} ALTER COLUMN {db_column} SET DEFAULT {default};\n'.format(
                            db_table=db_table,
                            db_column=db_column,
                            default=field.__db_default,
                            ))
            except Exception, e:
                print >> sys.stderr, "Could not generate SQL file. Manually set the defaults! {0}\n".format(e) * 10
    
    generate_default_sql(OrderShipLog)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In Java we use System.setProperty() method to set some system properties. According to this
I have a COM-Callable Wrapper on a .NET assembly. Some of the methods use
I heard that static methods should use only static variables in java. But, main
I have a service level methods, which make few changes to database and I
I want to use a graph database using php. Can you point out some
I will use LINQ-to-SQL when the database is ready and use the entities there
OK, so I understand how to use the ASP.net GridView control's paging. You set
In C# I have methods that use [WebMethod(EnableSession = true)] I consume them in
I have a base class that has methods that use a generic type in
I'm currently building a REST API. All GET methods currently use JSON as response

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.