Django空字段回退 [英] Django empty field fallback

查看:118
本文介绍了Django空字段回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存用户地址的模型.此模型必须具有first_namelast_name字段,因为一个人想设置收件人的地址(例如他的公司等).我想要实现的是:

I have a model that holds user address. This model has to have first_name and last_name fields since one would like to set address to a recipient (like his company, etc.). What I'm trying to achieve is:

  • 如果地址中的first_name/last_name字段已填写-请简单地返回该字段
  • 如果地址中的first_name/last_name字段为空-从指向正确的django.auth.models.User
  • 的外键中获取相应的字段数据
  • 我希望将其视为将出现在字段查找中的普通Django字段
  • 我不想创建一个方法,因为它是一种重构,并且Address.first_name/last_name在应用程序的各个位置(也包括模型形式等)中使用,所以我需要此方法尽可能地平滑,否则,我将不得不在很多地方进行修改.
  • If the first_name/last_name field in the address is filled - return simply that field
  • If the first_name/last_name field in the address is empty - fetch the corrresponding field data from a foreignkey pointing to a proper django.auth.models.User
  • I'd like this to be treated as normal Django field that would be present in fields lookup
  • I don't want to create a method, since it's a refactoring and Address.first_name/last_name are used in various places in the application (also in model forms, etc.), so I need this to me as smooth as possible, or else, I will have to tinker around in a lot of places.

推荐答案

此处有两个选项.第一种是创建一种方法来动态查找它,但是使用property装饰器,以便其他代码仍可以使用直接属性访问.

There are two options here. The first is to create a method to look it up dynamically, but use the property decorator so that other code can still use straight attribute access.

class MyModel(models.Model):
    _first_name = models.CharField(max_length=100, db_column='first_name')

    @property
    def first_name(self):
        return self._first_name or self.user.first_name

    @first_name.setter
    def first_name(self, value):
       self._first_name = value

这将始终引用first_name的最新值,即使相关的用户已更改.您可以像设置属性一样完全获取/设置属性:myinstance.first_name = 'daniel'

This will always refer to the latest value of first_name, even if the related User is changed. You can get/set the property exactly as you would an attribute: myinstance.first_name = 'daniel'

另一种选择是覆盖模型的save()方法,以便在保存时进行查找:

The other option is to override the model's save() method so that it does the lookup when you save:

def save(self, *args, **kwargs):
    if not self.first_name:
        self.first_name = self.user.first_name
    # now call the default save() method
    super(MyModel, self).save(*args, **kwargs)

通过这种方式,您不必更改数据库,但是仅在保存时刷新它-因此,如果相关的User对象被更改,但该对象没有更改,它将引用旧的User值.

This way you don't have to change your db, but it is only refreshed on save - so if the related User object is changed but this object isn't, it will refer to the old User value.

这篇关于Django空字段回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆