我有一个模特:
class Model(models.Model):
name =
我想为模型对象的每个组合存储一些值。这些值可以及时更改,并且它们不会通过数学函数链接。 什么是最聪明的方法呢?
也许我可以使用这个模型:
class Model_Relation(models.Model):
model1 = models.ForeignKey(Model, null=True, on_delete=models.PROTECT,
related_name='model1_relation')
model2 = models.ForeignKey(Model, null=True, on_delete=models.PROTECT,
related_name='model2_relation')
value1 = models.ForeignKey(Something, to_field='name',
on_delete=models.PROTECT, default ='something1'
related_name='...')
value2 = models.ForeignKey(Anotherthing, to_field='name',
on_delete=models.PROTECT, default ='anotherthing1'
related_name='...')
value3 = ...
class Meta:
unique_together = ("model1", "model2")
但写下所有的关系很长......
它可以帮助我在populate_script上设置默认值
for m1 in model.all():
for m2 in model.all():
m1.name_m2.name = add_model_relation(m1, m2, 'something1',
'anotherthing1', '...')
然后只在必要的地方进行更改,但无论如何都需要很长时间......
也许最好为模特添加一些字段或......我不知道......有什么建议吗?
编辑: 使用直通字段:
class Model(models.Model):
name = models.CharField(max_length=32, unique=True)
relations = models.ManyToManyField('self',
related_name='...', through='Model_Relation')
class Model_Relation(models.Model):
model1 = models.ForeignKey(Model, null=True, on_delete=models.PROTECT,
related_name='model1_relation')
model2 = models.ForeignKey(Model, null=True, on_delete=models.PROTECT,
related_name='model2_relation')
value1 = models.ForeignKey(Something, to_field='name',
on_delete=models.PROTECT, default ='something1'
related_name='...')
value2 = models.ForeignKey(Anotherthing, to_field='name',
on_delete=models.PROTECT, default ='anotherthing1'
related_name='...')
value3 = ...
class Meta:
unique_together = ("model1", "model2")
做三个m2m,每个值加一个?因此,只有在必要时才能确定关系