Tag Archives: unique together

Example of Django model unique together

unique_ together

The set of field names used together must be unique:

 unique_together = (("driver", "restaurant"),)

This is a tuple of tuples and must be unique when considered together. It is used by Django administrators and is enforced at the database level (that is, unique statements contain the corresponding statements)CREATETABLE

For convenience, when dealing with a single set of fields, unique_ Together can be a single tuple:

  unique_ together = (“driver”, “restaurant”)

  

A manytomanyfield cannot be included in unique_ Together( It’s not clear what that even means!) If you need to verify the uniqueness associated with a manytomanyfield , try signal or explicit through model

In validation error when constraints are violated, the unique_ Together error code

Introduction to official documents

generally acts on:

the setting field is unique, but there is a combination form, and it is not repeated

save users as the only user and course, but a user has multiple courses, so this method is used to save

This metadata is very important! It is equivalent to the joint constraint of the database

For example, suppose there is a user table, which contains the user’s name, date of birth, gender, native place and so on. The only requirement is that all users do not repeat, but now there are several “Zhang Wei”. How can we distinguish them( Don’t talk to me. This is not the issue

We can set that two users can’t be born in the same place at the same time and both are called “Zhang Wei”. Using this kind of joint constraint, we can ensure that the database can add users repeatedly (don’t talk about small probability with me). How to implement this constraint in Django’s model

Using unique_ Together , that is to say, unite only

For example:

  unique_together = (('name', 'birth_day', 'address'),)

In this way, even if there are two Zhang Wei who were born on the same day, they have different native places, that is, two different users. Once all three are the same, it will be rejected by Django. This metadata is often used in the background of admin, and forced to be applied to the database level

  unique_ Together receives a two-dimensional tuple ((XX, XX, XX,…), (), (), ()…). Each element is a tuple, representing a group of joint unique constraints. Multiple groups of constraints can be set at the same time. For convenience, when there is only one set of constraints, one-dimensional elements can be simply used, for example:

  unique_together = ('name', 'birth_day', 'address')

Union only cannot work on ordinary many to many fields

  unique_ Together = ((‘username ‘,’password’), (‘age ‘,’date’),) ා union is unique. When all fields in any tuple parameter are the same, they cannot be added