1
Defining the constraint is quite straight forward.
The tricky part for you is to create that one user if you randomly assign group numbers but no matter how you twist and turn it you would have a lot of SQL queries made since you need to check if user already exists.
class Person(models.Model):
firstname = models.CharField(max_length = 30)
group = models.IntegerField(max_length = 5)
class Meta:
unique_together = ("firstname", "group")
Then I guess something crude along the lines of (not tried and it’s very “sloppy”)
from random import randint
def assign_group_and_save():
rand_group = randint(1, 99999)
person, created = Person.objects.get_or_create(firstname=self.firstname, group=rand_group)
if not created:
#try again
return self.assign_group_and_save()
else:
return person
That being said, I would look into trying to fork this task of to some async task using Celery and have that create your username for you instead of letting your user wait for you to return to her.
Source:stackexchange.com