我想为多对多关系设置外键,而不必指定 through 字段或(在不影响现有逻辑的情况下指定它)。
监控.py
class QuoteMonitor(g.UserModel):
quote_services = m. OneToOneField(g.QuoteService)
引用.py
class Quote(g.UserModel):
name = m.CharField(max_length=512, default='New Quote')
services = m.ManyToManyField(g.Service, blank=True)
class Service(g.UserModel):
name = m.CharField(max_length=512, default='New Service')
我现在不能这样做,因为 g.QuoteService 模型不存在。该表由 django 多对多字段自动创建。
这可能吗?
编辑:
这question提供了类似的答案。
最佳答案
您可以为 django 自动创建的多对多关系创建一个非托管模型。
class QuoteService(models.Model):
quote = m.ForeignKey(g.Quote)
service = m.ForeignKey(g.Service)
class meta:
db_table = 'table-name-goes-here'
managed = False
然后您可以创建一个模型,通过 ForeignKey 或 1-1 字段引用 m2m 关系:
class QuoteMonitor(g.UserModel):
quote_service = m.OneToOneField(g.QuoteService)
注意:在创建初始模型后,您应该在第二次迁移中创建 QuoteMonitor。
关于python - 如何在 Django 中将外键设置为默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35041637/