Методы внутреннего объединения в Django возвращают неожиданные результаты

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.Не возвращает ни одного поля из объединенной таблицы MyBuffers

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.Бросает ошибку

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)
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.CASCADE)
    geog = models.PointField(geography=True, srid=4326) 
    class Meta:
        managed = False
        db_table = 'my_points'

Попробуйте следующий код

Я думаю, что select related работает только с внешними ключами. Поэтому если вы пытаетесь получить поля, отличные от внешних ключей, это приведет к ошибке. Ваш набор запросов должен быть

test= MyPoints.objects.select_related('projectid')
# To get radius
test.first().projectid.radius
Вернуться на верх