mysql - 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?
解决方案
推荐阅读
- r - 带有 invalidateLater() 的简单闪亮应用程序错误地丢弃了持久后台进程
- maven - 将 Kotlin 多平台项目发布到 mavenLocal 时如何设置 artifactId?
- python - 如何从幻灯片中提取的文本生成 xml 或 json?
- javascript - 如何使元素成为浏览器窗口的高度?
- node.js - TypeOrm创建连接方法迁移数据库建表失败
- sql - 仍然为 SQL 数据透视表中的列获取 NULL 值
- vb.net - “system.io.compression.zipfile”的类型初始化程序引发异常错误
- neo4j - Cypher:如何遍历除特定标签之外的任何关系
- html - 为什么 Firefox 不显示我的背景图片?
- d3.js - 基于增量计数器 D3 为折线图添加颜色