Django Model Unique Together example

Source: Internet
Author: User
Unique_together

This metadata is a very important one. It is equivalent to a federated constraint on the database.

For example, suppose you have a user table that holds information about the user's name, date of birth, gender, place of origin, and so on. Requirements are all users only do not repeat, but now there are several called "Zhang Wei", how to distinguish them. (Don't talk to me about the primary key, this is not the problem)

We can set no two users in the same place at the same time born and are called "Zhang Wei", the use of this joint constraint to ensure that the database can be repeatedly added users (and do not talk to me about the small probability problem). In the Django model, how do you implement this constraint?

Use Unique_together, which is the union unique.

Like what:

Unique_together = (' name ', ' Birth_day ', ' address '),)

In this way, even if there are two born on the same day, Zhang Wei, but their origin is different, that is, two different users. Once all three are the same, they are rejected by Django. This metadata is often used in the admin background and is enforced at the database level.

Unique_together receives a two-dimensional tuple ((Xx,xx,xx,...), (), (), () ...), each element is a tuple, representing a set of joint unique constraints, which can be set simultaneously with multiple sets of constraints. For convenience, you can simply use one-dimensional elements for a single set of constraints, such as:

Unique_together = (' name ', ' Birth_day ', ' address ')

The Union is the only one that cannot be used for common many-to-many fields.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.