0

I have two models:

class Foo(Model):

     special_id = IntegerField(primary_key=True)

class FooDetail(Model):

     special_id = IntegerField(primary_key=True)

special_id comes from an outside source -- it's a foreign key into another database. Yes, Foo and FooDetail should be combined into a single model -- but assuming I can't -- can I create a related field between the two models such that I can use it in queries (like in values or select_related)?

I could add a ForeignKey('FooDetail') in Foo, but I'd be essentially storing the special_id twice.

rrauenza
  • 6,285
  • 4
  • 32
  • 57
  • Related -- or almost the same -- question: https://stackoverflow.com/questions/34501313/django-model-foreign-key-as-primary-key – rrauenza Mar 29 '19 at 19:51

1 Answers1

0

If you want to use the ORM's features for related models, you should create a relationship (one-to-one in this case) between the two models. In one of the models you can (and should) then omit the special_id reference.


You can use the foreign key as a primary key in FooDetail, and if you keep special_id as a primary key in Foo, you'll be saving exactly the same type and amount of columns and data as in your example (namely one column in each that contains the relevant special_id).

What you get though is the benefit of a relationship and enforced integrity.

The only difference is that when you introduce a new special_id, you have to create Foo first to be able to point to it in FooDetail – hardly a big price to pay.


If you get a warning on setting the reference field to Foo to be the primary key then it might be that you defined it as a ForeignKey. You should define the field as a OneToOneField since you're dealing with a one-to-one relationship as noted above. The field is still technically a foreign key (= reference to the primary key of a row in another table) which is why I used this term; but it has a unique constraint that allows it to be used as a primary key.

Endre Both
  • 5,540
  • 1
  • 26
  • 31
  • yeah, that's what I was afraid of. Not a big deal, but it adds an unneeded primary key to the FooDetail. – rrauenza Mar 29 '19 at 19:33
  • Django gives a big warning about using the foreign key as the primary key, so i've gone ahead and left special_id AND the foreign key... which both have the same value. – rrauenza Mar 30 '19 at 20:56