从另一个mod获取值列表

2024-05-19 12:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我安装了一个第三方应用程序,它基本上有5个字段:id、name、state、geocode、geometry。你知道吗

我创建了一个新的应用程序,只需要从另一个模型的“name”字段导入值。你知道吗

所以我基本上是这样做的:

from django.db import models
from django.contrib.auth.models import User
from django.contrib.gis.geos import Point
from brasil_municipios.models import Municipio #which is the third party app

class Escritorio(models.Model):
    nomeescritiorio = models.CharField(max_length=255)
    cidade = models.OneToOneField(Municipio.objects.values_list('name').order_by('name')[0:10], on_delete=models.PROTECT, null=True)

出现了这个错误:

AssertionError: OneToOneField(<QuerySet [('ABADIA DE GOIÁS',), ('ABADIA DOS DOURADOS',), ('ABADIÂNIA',), ('ABAETETUBA',), ('ABAETÉ',), ('ABAIARA',), ('ABARÉ',), ('ABATIÁ',), ('ABAÍRA',), ('ABDON BATISTA',)]>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'

我已经尝试过其他方法来解决这个问题,使用filter()、get()等等,但是所有这些方法都得到相同的错误。你知道吗


Tags: thedjango方法namefromimport应用程序model
1条回答
网友
1楼 · 发布于 2024-05-19 12:26:09

I created a new app which I need to import only the values from the 'name' field from the other model.

你不能“从另一个模型导入值”——这不是它的工作方式。您要做的是将模型链接在一起,以便底层的“escritorio”表记录知道与它们相关的“municipio”表记录的主键(这就是OneToOneField实际上正在做的事情)。然后,从“escritorio”中存储的外键,可以读取相关“municipio”记录的“name”值。你知道吗

这样,您只需将相关模型的名称传递给OneToOne字段,然后就可以从紧跟关系的Escritorio实例中获取相关的市政名称,即escrotorio.cidade.name。你知道吗

如果在使用Escritorio模型时经常需要使用此值,可以通过向Escritorio添加只读属性来优化可读性:

class Escritorio(models.Model):
    nomeescritiorio = models.CharField(max_length=255)
    cidade = models.OneToOneField(Municipio, on_delete=models.PROTECT)

    @property
    def name(self):
        return self.cidade.name

它允许您只写escritorio.name(实际上是简单的快捷方式)

当然,您希望通过强制ORM在加载escritorio时总是加载相关的municipio值来优化性能,这样您就可以将所有内容都放在一个db查询中,而不需要一个查询来获取escritorio,另一个查询来获取相关的municipio。您可以通过using ^{}来实现这一点,可以在知道需要名称时直接实现,也可以通过为Escritorio模型提供自定义管理器和查询集类来实现。你知道吗

NB:您当然需要为您感兴趣的每个市政记录创建escritorio实例-django和RDMB都不会自动为您执行此操作。你知道吗

相关问题 更多 >