[英]django two foreign keys unique record
I have three django models: 我有三个django型号:
class Item(models.Model):
itemid = models.IntegerField(default=0, unique=True)
class Region(models.Model):
regionid = models.IntegerField(default=0, unique=True)
class Price(models.Model):
regionid = models.ForeignKey(Region)
itemid = models.ForeignKey(Item)
Now my issue is this: 现在我的问题是:
I need to have Price be unique for the Item and Region combination (eg itemid = 1 & regionid = a therefore there can only be one Price that can have foreign keys of itemid = 1 and regionid = a). 我需要让Price对于Item和Region组合是唯一的(例如itemid = 1&regionid = a因此只能有一个Price可以使用itemid = 1和regionid = a的外键)。
Is there any way to enforce that relationship? 有没有办法强制执行这种关系?
You should take a look at unique together ! 你应该看看独特的一起 ! It may solve your issue.
它可以解决您的问题。
Django does not yet support compound indicies. Django尚未支持复合指数。 The accepted solution is to register a post_syncdb signal handler -- https://docs.djangoproject.com/en/1.6/ref/signals/#post-syncdb
接受的解决方案是注册post_syncdb信号处理程序 - https://docs.djangoproject.com/en/1.6/ref/signals/#post-syncdb
Here's the template (you'll need to fill in the appropriate details): 这是模板(您需要填写相应的详细信息):
from django.db import connection
from django.db.models.signals import post_syncdb
def callback(sender, **kwargs):
cur = connection.cursor()
cur.execute('CREATE UNIQUE INDEX ...')
post_syncdb.connect(callback, sender=app.models)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.