简体   繁体   English

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

[英]How can I create a queryable alias for a foreign-key field in a Django model?

I have a series of models that have fields to be migrated to a FK.我有一系列模型,这些模型具有要迁移到 FK 的字段。

Before

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

After

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')

Assuming I have queries in my views that do lookups on the flange field, how can I create an alias?假设我的视图中有对flange字段进行查找的查询,我如何创建别名? I have many models that are being restructured in the manner above and would like to use this method so that I don't have to replace every use of that field in views, etc.我有许多正在以上述方式重组的模型,并希望使用这种方法,这样我就不必在视图等中替换该字段的每次使用。

Would appreciate any pointers;希望得到任何指点; all info on model aliases I've found only work for same-model fields.我发现所有关于模型别名的信息仅适用于相同模型的字段。

The easiest solution would be to create a @property :最简单的解决方案是创建一个@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

Then, in any of the views if you have a sizing_obj.flange it won't be affected at all.然后,在任何视图中,如果您有sizing_obj.flange它根本不会受到影响。

However, you cannot use it in queryset or filters etc.但是,您不能在查询集或过滤器等中使用它。

aliasName = models.ForeignKey(modelName, to_field='fieldName', on_delete=models.CASCADE)

This is the format for aliasing in Django Foreign Key这是 Django 外键中的别名格式

class Sizing(models.Model):
    btu_hour = models.IntegerField()
    configuration = models.ForeignKey(Configuration)
    ### WHAT I'D LIKE; alias only ###
    flangeNew = models.ForeignKey(Configuration, to_field='flange', on_delete=models.CASCADE)

class Configuration(models.Model)
    flange = models.ForeignKey('parts.Router')

This is the solution of aliasing in new version of Django这是新版Django中别名的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM