I have two database tables which are logically related through a CharField
. For example, a survey response which asks for a phone number, and a person which has a phone number:
class SurveyResponse(Model):
phone_number = CharField()
favorite_brand_of_soda = CharField()
person = JoinedOneToOneField("Person", from_field="phone_number", to_field="phone_number")
class Person(Model):
phone_number = CharField()
name = CharField()
Is it possible to create a Field — like the JoinedOneToOneField
in this example — which would allow me to query for the Person
who is related to the SurveyResponse
, if one exists?
For example, so that I can use select_related
to ensure that queries are efficient:
>>> responses = SurveyResponse.objects.all().select_related("person")
>>> print [ (r.person.name, r.favorite_brand_of_soda) for r in responses ]
And so that I can access the related Person
through an attribute lookup:
>>> response = SurveyResponse.objects.get(…)
>>> print response.person.name
I know that ForeignKey
accepts a to_field=
parameter, but this won't quite do it because the database will try to enforce referential integrity through that field, which is inconsistent with the data model.
In other words, something similar to SQLAlchemy's relationships.
PLEASE NOTE: I do not want to use a FOREIGN KEY
: the records that I'm dealing with are pencil-and-paper forms, and there is no guarantee that numbers will match. Before you suggest that I'm wrong in this, please consider that this is a simplified example, and the fact that I really, honestly, do know how to use a ForeignKey
field.