首页 > 解决方案 > How to mimic unique_together behaviour for many-to-many fields?

问题描述

I need to treat three fields from model as unique . The problem is that one of them is ManyToManyField so i can't use Django built-in unique_together functionality. How would you handle this problem? Database i'm using is MySQL.

Example:

class A(models.Model):
    name = models.CharField(max_length=255)

class B(model.Model):
    name = models.CharField(max_length=255)
    other_field = models.CharField(max_length=255)
    a_m2m = models.ManyToManyField(A, blank=True)

And i want name, other_field and all fields from m2m relation unique together.

So following "rows" for B are treated as a whole and are unique (with m2m):

name: 1, other_field: 1, a_m2m: (1, 2, 3)
name: 1, other_field: 1, a_m2m: (1, 2)
name: 1, other_field: 2, a_m2m: (1, 2, 3)
name: 1, other_field: 1, a_m2m: (1, 2, 4)

How would you do it in Django/MySQL?

标签: mysqldjango

解决方案


推荐阅读