Hello i am testing Django authentication and nesting user data. I created a simple MyProfil model for my users. I wanted to test making a custom id and set the primary_key=True as id = models.UUIDField.
models.py
class MyProfil(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
aboutme = models.TextField(max_length=300, blank=True)
city = models.TextField(max_length=300, blank=True)
so far everything works in my favor but i have a question, that i could not answer myself even after reading the django doc.
Question
Does primary_key=True on my id Field also mean unique or do i have to declare it?
If True , this field is the primary key for the model. If you don't specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don't need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior.
unique=True sets the field to be unique i.e. once entered a value in a field, the same value can not be entered in any other instance of that model in any manner. It is generally used for fields like Roll Number, Employee Id, etc which should be unique.
If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.
Yes. Since a primary key means a value that can uniquely identify an object. In the documentation on the primary_key parameter, we see:
Field.primary_keyIf
True, this field is the primary key for the model.If you don’t specify
primary_key=Truefor any field in your model, Django will automatically add anAutoFieldto hold the primary key, so you don’t need to setprimary_key=Trueon any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.
primary_key=Trueimpliesnull=Falseandunique=True. Only one primary key is allowed on an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With