Django 内部连接方法 return 意外结果

Django inner join methods return unexpected results

我是 Django 的 ORM 新手,尽管参考了 SO 上的 documentation and other answers,但仍对内部连接约定感到困惑。我有两个 tables - MyPointsMyBuffersprojectid 一对一相关(table 中没有重复项)。我的目标是使用 projectid 上的内部连接获取 radius 字段。尽管我已经定义了一个外键,但我第一次尝试从 MyBuffers return 中获取所有字段时没有从连接的 table 中获取任何字段,而我第二次尝试从 MyBuffers 中获取一个字段=16=]错误。这里的语法或方法有什么问题?关键列是否应该以不同的方式命名?任何建议将不胜感激!

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 不是 return 加入的 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 一个错误

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 相关只适用于外键。因此,如果您尝试获取外键以外的字段,则会引发错误。您的查询集必须是

test= MyPoints.objects.select_related('projectid')
# To get radius
test.first().projectid.radius