Skip to main content
 首页 » 编程设计

python之如何为 Django 模型中的外键字段创建可查询的别名

2025年04月02日32davidwang456

我有一系列模型,这些模型的字段要迁移到 FK。

之前

class Sizing(models.Model: 
    btu_hour = models.IntegerField() 
    flange = models.ForeignKey('parts.Router') 

之后

class Sizing(models.Model): 
    btu_hour = models.IntegerField() 
    configuration = models.ForeignKey(Configuration) 
    ### WHAT I'D LIKE; alias only ### 
    flange = Alias(to='configuration__flange') 
 
class Configuration(models.Model) 
    flange = models.ForeignKey('parts.Router') 

假设我在我的 View 中有对 flange 字段进行查找的查询,我该如何创建别名?我有许多模型正在以上述方式重组,并且想使用这种方法,这样我就不必在 View 等中替换该字段的每次使用。

将不胜感激任何指点;我发现有关模型别名的所有信息仅适用于相同模型的字段。

请您参考如下方法:

最简单的解决方案是创建一个@property:

class Sizing(models.Model): 
    btu_hour = models.IntegerField() 
    configuration = models.ForeignKey(Configuration) 
 
    # define the property flange 
    @property 
    def flange(self): 
        return self.configuration.flange 

然后,在任何 View 中,如果您有一个 sizing_obj.flange,它根本不会受到影响。

但是,您不能在查询集或过滤器等中使用它。