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

  • Home
  • SEARCH
  • 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 5971121
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T20:28:21+00:00 2026-05-22T20:28:21+00:00

Assume a django model with two fields: – created – modified Each field are

  • 0

Assume a django model with two fields:
– created
– modified
Each field are integers, unique and ever-increasing in value. An object should have the same value for created and modified when saved the first time, and the modified field should be increated to the next free value larger than itself on each save.

I’ve created the following fields for the purpose:

class CreatedVerisonField(models.BigIntegerField):
    update_on_each_save = False

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('editable', False)
        kwargs.setdefault('blank', True)
        kwargs.setdefault('unique', True)
        models.BigIntegerField.__init__(self, *args, **kwargs)

    def pre_save(self, model, add):
        if add or self.update_on_each_save:
            value = self.get_next_value(model)
            setattr(model, self.attname, value)
            return value
        else:
            return super(CreatedVerisonField, self).pre_save(model, add)

    def get_next_value(self, model):
        objs = model.__class__.objects.all()
        fields = self._get_fields(model)
        if objs:
            # new version is max of all version fields + 1
            value = max(objs.aggregate(*map(lambda x: Max(x), fields)).values()) + 1
        else:
            value = 1
        return value

    def _get_fields(self, model):
        fields = []
        for f in model._meta.fields:
            if isinstance(f, CreatedVerisonField):
                fields.append(f.db_column if f.db_column else f.name)
        return fields

class ModifiedVersionField(CreatedVerisonField):
    def __init__(self, *args, **kwargs):
        self.update_on_each_save = True
        CreatedVerisonField.__init__(self, args, kwargs)

A simple test class using these fields:

class TestModel(models.Model):
    created = CreatedVerisonField()
    modified = ModifiedVersionField()

When creating and saving “TestModel” objects from multiple threads, I get IntegretyError due to the unique-constraint is violated. Looking add the pre_save code, it’s quite obvious that this race exists. How do I fix this?

  • 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-05-22T20:28:21+00:00Added an answer on May 22, 2026 at 8:28 pm

    The only way to do thread-safe database access is to lock the tables before access. A cursory search online turned up this snippet: http://djangosnippets.org/snippets/2039/. Maybe you can do something with that. The Django documentation’s section on transactions will be useful to you as well: https://docs.djangoproject.com/en/dev/topics/db/transactions/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Assume the following: models.py class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body
I have the following Django Model which retrieves 3 records from a database. The
I have a model which is essentially just a string (django.db.models.CharField). There will only
I'm new to Django and still having some problems about simple queries. Let's assume
I'm trying to store sections of a document in a Django app. The model
I found a custom field model ( JSONField ) that I would like to
Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker
Assume java 1.6 and leopard. Ideally, it would also be nice to get a
(assume php5) consider <?php $foo = 'some words'; //case 1 print these are $foo;
Assume you are doing something like the following List<string> myitems = new List<string> {

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.