Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Does "primary_key=True" also mean "unique"?

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?

like image 792
black_hole_sun Avatar asked Sep 27 '19 17:09

black_hole_sun


People also ask

What is primary_key true in Django?

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.

What is unique true Django?

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.

What does null true mean in Django?

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.

What is verbose name in Django?

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.


1 Answers

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_key

If True, this field is the primary key for the model.

If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField 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. For more, see Automatic primary key fields.

primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.

like image 176
Willem Van Onsem Avatar answered Sep 19 '22 01:09

Willem Van Onsem