6

I'd like the exact same thing as django.contrib.contenttypes.generic.GenericForeignKey, but OneToOne instead of ForeignKey. I thought an easy (albeit marginally inelegant) workaround was to add unique=True to the field in question, but that borks.

tshepang
  • 12,111
  • 21
  • 91
  • 136
jMyles
  • 11,772
  • 6
  • 42
  • 56

1 Answers1

6

Use unique_together?

Any combination of the content_type field and the ID field is a unique identifier for one object, therefore 1 to 1.

http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 1
    I'm also having the same issue. Using unique_together enforces the uniqueness of the relation in the database, but I still need to refer to it as my_foreign_key.objects.all()[0]. Is there any way to refer to it just as my_foreign_key, as a normal OneToOne field? – duduklein Jan 13 '12 at 14:44
  • @duduklein You are free to set up any python methods on your class, like `@property def my_foreign_key(self) return foo` - anyways, it's standard practice to ask new questions if you can't find an answer. – Yuji 'Tomita' Tomita Jan 13 '12 at 17:11