Take the 2-minute tour ×

I've got two models: Common and ARecord. ARecord has a ForeignKey relationship to Common. I want to ensure that ARecord is unique with a combination of items from ARecord and Common.

class Common(models.Model):
    NAIC_number = models.CharField(max_length=5)
    file_location_state = models.CharField(max_length=2)
    file_location_code = models.CharField(max_length=2)

class ARecord(models.Model):
    common = models.ForeignKey(Common)
    coverage_code = models.CharField(max_length=6)
    record_type = models.CharField(max_length=1)

    class Meta:
        unique_together = ('coverage_code', 'common__NAIC_number')

However, when I attempt to access the foreign key object property via the usual double underscore, I get a model validation error.

`arecord.arecord: "unique_together" refers to common__NAIC_number, a field that doesn't exist. Check your syntax.`

This seems like it should be possible and, a slightly different question was asked that indicates it is , but perhaps I'm missing something obvious?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

As Manoj implies, you can't do this with unique_together, because that is a database constraint and the sort of thing you want can't be done with database constraints.

Instead, you want do this programmatically, probably via model validation, which will ensure that no instances are created that violate your constraint.

share|improve this answer
That makes sense. Unfortunately, I'm running Django v1.0 so no validators for me. And even if I could, I'm not inclined to do it that way; seems like it would be waaay to easy to jack up my database during a save. Common is saved before ARecord, so Common could be successfully saved before I get to the validation point. Then I'd have to delete Common, but which one? Anyway, I'm going to move coverage_code up to the Common class. I thought I'd have to do that anyway, but I was hoping for a little magic. Alas. –  ghiotion Aug 31 '10 at 19:07

This doesn't make sense to me. The documentation defines unique_together thus:

This is a list of lists of fields that must be unique when considered together. It's used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).

(Emphasis added)

I don't know how an UNIQUE statement can be added at the database level for such a case (using one column in the current table and another in a different table accessed through a foreign key). I hope those who know better about databases will correct me if I am wrong.

share|improve this answer

Your Answer


