为什么这种多对多关系会在我没有要求的情况下使用 Django ORM 进行更改?
我与指标类有递归 M2M 关系。指标是一个 int,或者是由 2 个指标计算得出的值:
class Indicator(models.Model):
params = models.ManyToManyField('self',
verbose_name=__(u'parameters'),
related_name='params_of',
blank=True, null=True)
type = models.CharField(max_length=64, verbose_name=__(u'type'))
def get_value(self, record):
# etc
根据类型,get_value 不会执行相同的操作。它可以只返回数值,也可以根据 params
属性中每个参数的数值计算出一个值。正如您所看到的,params
是一种递归的 m2m 关系。
现在我的问题是,我有以下指标:
- 男性
- 女性
- 总流行
- 男性比例
如果我添加 men
和 women
作为 total pop
的参数,一切都很好,我得到了动态计算的总流行数。但是,如果我随后将 men
和 total pop
添加为 menratio
的参数,就会自动total pop
获取男性比例
作为参数。它破坏了一切。
这是为什么?我怎样才能避免它?
I have a recursive M2M relationship with an indicator class. An indicator is a int, or a calculated value from 2 indicators:
class Indicator(models.Model):
params = models.ManyToManyField('self',
verbose_name=__(u'parameters'),
related_name='params_of',
blank=True, null=True)
type = models.CharField(max_length=64, verbose_name=__(u'type'))
def get_value(self, record):
# etc
According to the type, get_value doesn't do the same things. It can just return the numerical value or calculate a value from the numerical value of each parameters from the params
attribute. As you can see params
is a recursive m2m relationship.
Now my problem is that, I have the follwoing indicators:
- men
- women
- total pop
- men ratio
If I add men
and women
as parameters of total pop
, everything is fine, and I get my total pop dynamically calculated. But if I then add men
and total pop
as parameters to men ratio
, then total pop
automatically get men ratio
as a parameter. It breaks everything.
Why is that? How can I avoid it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 中的 M2M 关系默认是对称的,即在 M2M 中,如果 a 与 b 相关,则 b 也与 a 相关。要阻止这种情况,请使用 symmetry=False ,
您的参数将变为:
M2M relations in Django are symmetric by default ie in an M2M, if a related to b then b also related to a. To stop this, use
symmetrical=False
your params would become: