Domanda

I have three django models:

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 (e.g. itemid = 1 & regionid = a therefore there can only be one Price that can have foreign keys of itemid = 1 and regionid = a).

Is there any way to enforce that relationship?

È stato utile?

Soluzione

You should take a look at unique together! It may solve your issue.

Altri suggerimenti

Django does not yet support compound indicies. The accepted solution is to register a post_syncdb signal handler -- 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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top