1

I have this model

class Inscription(models.Model):
    person = models.ForeignKey(Person)
    congress = models.ForeignKey(Congress)
    folio = models.IntegerField(max_length=4, editable=False)

I need the folio attribute to be unique within the same congress, but repeatable in the table, but it's important that generated random numbers are not repeated (instead of validating if it already exists and then generate a new one).

Is there any way to achieve this? It doesnt matter if the work is to be done in Django or PostgreSQL

Thank you for reading.

1 Answer 1

2

if you can change the type of folio field to CharField, then you can use uuid.

import uuid
x = str(uuid.uuid1())

The x will always be unique and you will never need to check the value for duplicate in the Model. Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but the folio must be a number between 0 and 1000, even if it's a CharField, also it must be unique for the congress it's related to, not in the whole table. Example: There's the congress1 and I have 50 people attending to it, with their random folios, lets say person8 has folio number 472 Then, the next congress (congress2) may have a person1 with folio nomber 472
if that is the case move the folio field to congress.
the folio is a number that identifies each participant (not all the people stored paticipate in every congress, and previous participant may partipate again)
In that case you can use random module to generate a random integer import random r = random.Random() random_int=r.randint(0,1000). This will give you random integer. After that filter with the generated random int and see if there is any entry with the same congress object. If there is then try again with the above code else save.
Yes, actually that's the way it works now (in the database), but I was looking for a method that prevent the already existing numbers from being generated again (so that no validation will be necessary)

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.