This is my project setup, using standard Django startproject command with a single app:
Python 3.5.1
Django 1.9.7
PostgreSQL 9.5.3
Ubuntu 16.04
The app's models.py defines 2 models:
from django.db import models
class A(models.Model):
n = models.PositiveIntegerField(primary_key=True)
class B(models.Model):
a = models.ForeignKey(A, blank=True, null=True)
m = models.CharField(max_length=20, db_index=True)
class Meta:
unique_together = ('a', 'm')
def __str__(self):
return '%s' % self.m
Here's my management command called execute.py to create instances of B:
from multiprocessing import Pool
from django import db
from django.core.management.base import BaseCommand
from .models import B
M = 'abcdef'
def create():
obj, created = B.objects.get_or_create(m=M, defaults={'a': None})
if created:
print('obj=%s' % obj)
class Command(BaseCommand):
def handle(self, *args, **kwargs):
B.objects.filter(m=M).delete()
db.connections.close_all()
n = 4
pool = Pool(processes=n)
results = []
for _ in range(n):
result = pool.apply_async(create)
results.append(result)
pool.close()
for result in results:
result.get()
pool.join()
Running python manage.py execute causes 4 objs to be created instead of just 1. This is not always the case though. Sometimes, there are only 3 or even just 1 object created:
obj=abcdef
obj=abcdef
obj=abcdef
obj=abcdef
Am I missing something to enforce the uniqueness here?