[Fixed]-Can a django model have unique and a shared non unique field?

0👍

You can set null=True on the field and set the field to None. A column with a UNIQUE constraint can have multiple NULL values.

You’ll have to be explicit when using forms or default values. The default for a CharField is an empty string, and empty form values will also be saved as an empty string. In both cases you need to explicitly set the value to None instead.

👤knbk

1👍

import uuid   
verify_key = models.CharField(max_length=50,
                              unique=True,
                              default=uuid.uuid4)

If you are using django 1.8 you also have UUIDField. Here’s Django doc.

0👍

You can’t do this in your model class.

You just need to add null=True to the field and set Model.verify_key=None whenever you create an instance. Also, you can define a custom model form to deal with this in the forms.

👤pythad

0👍

You can’t set an empty string, but you can set the value to NULL. NULL is not equals to NULL when Django check for uniqueness.

Leave a comment