不想询问是否可以在CharField字段中使用populate_from选项来预填充其他字段中的字段,就像slug字段的示例一样。
class Post(models.Model):
***name***= models.CharField(max_length=50)
slug = extension_fields.AutoSlugField(populate_from='***name***', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
让我们说,
class Employee(models.Model):
eid= models.CharField(primary_key = True)
lastname = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
middlename = models.CharField(max_length=50, null=True)
现在我不想添加新的CharField全名。我想要从姓氏,名字和中间名字段填充全名。
fullname = models.CharField(populate_from = "***i don't know what to do here***")
请帮忙......
答案 0 :(得分:1)
您可以在Employee
模型的保存方法中执行此操作。
def save(self, *args, **kwargs):
self.fullname = '{0} {1} {2}'.format(self.firstname, self.middlename, self.lastname)
super(Employee, self).save(*args, **kwargs)
为此,您可能必须将fullname
字段保留为可选字段。否则,您可能会在表单中遇到错误。
答案 1 :(得分:1)
这可能是一个解决方案,没有populate_from
class Employee(models.Model):
eid= models.CharField(primary_key = True)
lastname = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
middlename = models.CharField(max_length=50, null=True)
fullname = models.CharField(max_length=50)
def save(self):
self.fullname = "%s %s %s" % (lastname, firstname, middlename)
super(Employee, self).save()
或使用AutoSlugField和 populate_from
class Employee(models.Model):
eid= models.CharField(primary_key = True)
lastname = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
middlename = models.CharField(max_length=50, null=True)
fullname = AutoSlugField(populate_from=lambda instance: instance.employee.get_full_name())
def get_full_name(self):
fullname = "%s %s %s" % (lastname, firstname, middlename)
return fullname
答案 2 :(得分:1)
这是一个不需要覆盖save
函数的选项:
class Employee(models.Model):
def get_fullname(self):
return '{} {} {}'.format(self.lastname, self.firstname, self.middlename)
eid= models.CharField(primary_key = True)
lastname = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
middlename = models.CharField(max_length=50, null=True)
fullname = property(get_fullname)
如果您不需要fullname
lastname
,firstname
和middlename
分别编辑def my_process_executor(req, semaphore=None):
try:
p = multiprocessing.Process(target=do_stuff,args=(req,))
p.daemon = False
p.start()
p.join(MAX_SECONDS_WAITING_FOR_PROCESS)
if p.is_alive():
# Too much time running, kill it!
p.terminate()
p.join()
finally:
if semaphore:
semaphore.release()
该选项,因为它不会显示为管理员中的字段,但将结果存储在数据库中在调用时获取值