简体   繁体   中英

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.

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? 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 :

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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