I am new to Django's ORM and am confused by inner join conventions despite having consulted the documentation and other answers on SO. I have two tables - MyPoints
and MyBuffers
that are one-to-one related by projectid
(no duplicates in either table). My goal is to fetch the radius
field using inner join on projectid
. Even though I have defined a foreign key, my first attempt at fetching all of the fields from MyBuffers
returns nothing from the joined table, and my second attempt at fetching one field from MyBuffers
errors. What is wrong with the syntax or methodology here? Should key columns be named differently? Any advice would be greatly appreciated!
models.py
from django.contrib.gis.db import models
class MyBuffers(models.Model):
id = models.BigAutoField(primary_key=True)
projectid = models.CharField(max_length=25, unique=True)
radius = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'my_buffers'
class MyPoints(models.Model):
id = models.BigAutoField(primary_key=True)
projectid = models.ForeignKey('MyBuffers', max_length=25, on_delete=models.DO_NOTHING, to_field='projectid', db_column='projectid')
geog = models.PointField(geography=True, srid=4326)
class Meta:
managed = False
db_table = 'my_points'
views.py
from .models import MyPoints
from .models import MyBuffers
1.Does not return any fields in from the joined MyBuffers
table
test = MyPoints.objects.select_related('projectid')
test.first().__dict__
{'_state': <django.db.models.base.ModelState object at 0x7f3e21786520>, 'id': 5808, 'projectid_id': 'foobar1', 'geog': <Point object at 0x7f3e21738910>}
2.Throws an errors
test= MyPoints.objects.select_related('projectid__radius')
test.first().__dict__
django.core.exceptions.FieldError: Non-relational field given in select_related: 'radius'. Choices are: (none)
I think select related only works in foreign keys. So if you are trying to get fields other than foreign keys it will throw an error. Your queryset must be
test= MyPoints.objects.select_related('projectid')
# To get radius
test.first().projectid.radius