I've got two models that look kind of like this:
class People(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=125, blank=True)
age = models.IntegerField(blank=True)
class Income(models.Model):
id = models.IntegerField(primary_key=True)
person_id = models.IntegerField(blank=True, null=True)
income = models.IntegerField(blank=True, null=True)
I want to be able to fetch any number of people and their related income in one query. But since there is no foreign key here, I can't do People.objects.filter(age=40).select_related('income')
. How do I make such a query without making a raw query? If it's not possible, what is the best way to alter the tables in order to make such a query?
Django expects ForeignKey
objects to simply have the name yourname_id
(although even that is overridable). Since Django also has support for databases without real foreign key support every bit for foreign key support is handled by Django itself instead of the database so there is no real need for database foreign keys. Except requiring database consistency that is (there are certain race conditions where it can be convenient to have this).
In most cases however, this will work without any foreign keys in your database (note that the id
column is added implicitly by Django):
class People(models.Model):
name = models.CharField(max_length=125, blank=True)
age = models.IntegerField(blank=True)
class Income(models.Model):
person = models.ForeignKey(People, blank=True, null=True)
income = models.IntegerField(blank=True, null=True)