我正在尝试这样做
nvc = models.ForeignKey(Nvc)
slug = AutoSlugField(max_length=50, unique=True, populate_from=('channel_index','nvc__mac_address'))
channel_index = models.IntegerField()
...
其中nvc是带有字段mac_address的外键,而channel index是本地字段
我的尝试基于AutoSlugField(autoslugfield)中显示的与“unique_with”一起使用的内容
# minimum date granularity is shifted from day to month
slug = AutoSlugField(populate_from='title', unique_with='pub_date__month')
但是我收到了这个错误
'NvcChannel'对象没有属性'nvc__mac_address'
有可能做我想做的事吗?如果是的话,我哪里出错?
我看了这个问题override save to execute code 想出了这个
def save(self, *args, **kwargs):
if not self.pk:
self.slug = AutoSlugField(max_length=50, unique=True, populate_from=('channel_index',self.nvc.mac_address))
super(NvcChannel, self).save(*args, **kwargs)
答案 0 :(得分:1)
nvc__mac_address
仅用于数据库查找(通常使用filter()
)。您正在尝试访问检索到的对象的字段,因此您应该使用nvcchannel.nvc.mac_address