为对象赋予与其外键字段相同的字段值

时间:2019-10-05 04:05:52

标签: django django-models

摘要:我有两个相关的模型,希望它们共享一个字段(zip_code):

class Business(models.Model):
    #other fields
    zip_code = models.CharField(max_length = 10)
 class Job(models.Model):
    business = models.ForeignKey(Business, on_delete = "models.CASCADE") 
    zip_code = business.zip_code #Does not work

完整说明:

我正在尝试创建工作委员会网站。用户输入邮政编码,应返回指定半径的作业。这是我的models.py:

class Business(models.Model):
    name = models.CharField(max_length = 150)
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 150)
    zip_code = models.CharField(max_length = 10)
    state = models.CharField(max_length = 30)
    phone_number = models.CharField(max_length = 10)

    def __str__(self):
        return self.name +", " + self.address + ", " + self.state

class Job(models.Model):
    business = models.ForeignKey(Business, on_delete = "models.CASCADE")
    title = models.CharField(max_length = 100)
    description = models.CharField(max_length = 500)
    zip_code = business.zip_code

    def __str__(self):
        return self.title + " - " + self.business.name

尝试通过邮政编码过滤Job个对象时:

jobs_in_zip = Job.objects.all().filter(zip_code = zip_code)

我意识到Job模型没有zip_code字段。我试图这样更新模型:

class Job(models.Model):
    business = models.ForeignKey(Business, on_delete = "models.CASCADE")
    zip_code = business.zip_code

但这返回了AttributeError: 'ForeignKey' object has no attribute 'zip_code'

我应该怎么做?提前致谢。

PS:如果我脑海中有个更好的标题,请随时进行更改,但我认为我没有明确地定义问题。

1 个答案:

答案 0 :(得分:1)

请在下面找到一个示例。本质上,您需要覆盖save类的Job方法:

class Algorithm(models.Model):
    name = models.CharField(max_length=120, unique=True)

class JobLog(models.Model):
    task_id = models.CharField(max_length=120, unique=True, primary_key=True)
    task_name = models.CharField(max_length=120, null=True)
    algorithm = models.ForeignKey(Algorithm, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        self.task_name = self.algorithm.name + "-" + self.task_id
        super(JobLog, self).save(*args, **kwargs)

出于您的目的:

class Job(models.Model):
    business = models.ForeignKey(Business, on_delete = "models.CASCADE")
    title = models.CharField(max_length = 100)
    description = models.CharField(max_length = 500)
    zip_code = business.zip_code

    def __str__(self):
        return self.title + " - " + self.business.name

    def save(self, *args, **kwargs):
        self.zip_code = self.business.zip_code
        super(Job, self).save(*args, **kwargs)
相关问题