通过django中的OnetoOne密钥访问数据

时间:2014-04-15 04:30:29

标签: python mysql django

我使用OnetoOne Model键连接了两个模型。

class Job_expectation(models.Model):
    SLAB_CHOICES = (
        ('H', 'Hourly'),
        ('W', 'Weekly'),
        ('M', 'Monthly'),
    )
    EMPLOYER_CHOICES = (
        ('I', 'Individual'),
        ('C', 'Corporate'),
    )
    TYPE_CHOICES=(
        ('P','Part time'),
        ('F','Full time'),
        ('I','Internship'),
        ('L','Freelancing'),
        )
    readytoworkas           =   models.OneToOneField(Readytoworkas)
    salary_slab             =   models.CharField(max_length=1,choices=SLAB_CHOICES,default='M')
    employer_type           =   models.CharField(max_length=1,choices=EMPLOYER_CHOICES,default='C')
    industry                =   models.ForeignKey(organization_sector)
    state                   =   models.ForeignKey(State, related_name="Preferred State of Work")
    city                    =   models.ForeignKey(City, related_name="Preferred City of Work")
    region                  =   models.ForeignKey(Region, related_name="Preferred Region of Work")
    shift_type              =   models.ManyToManyField(Slot_preference)
    job_type                =   models.CharField(max_length=1,choices=TYPE_CHOICES,default='F')
    min_salary              =   models.IntegerField(verbose_name="Minimum expected Salary")
    max_salary              =   models.IntegerField(verbose_name="Maximum expected Salary")
    negotiable              =   models.BooleanField(verbose_name="Is your salary negotiable?")`

class Readytoworkas (models.Model):
    employee_id     = models.ForeignKey(Employee,on_delete=models.DO_NOTHING)
    readytoworkas   = models.ForeignKey(Jobs)`

在Readytoworkas模型上进行的查询结果是一个列表。对于列表中的每个元素,我想访问Job_expectation表中的相应条目。

怎么做?这就是我现在要做的。

skilllist   = Readytoworkas.objects.filter(employee_id=employee)
      for i in skilllist:
        job_expect        =   Job_expectation.objects.get(readytoworkas=i)
        i.employer_type   =   job_expect.employer_type
        i.job_type        =   job_expect.job_type
        i.shift_type      =   job_expect.shift_type
        i.min_salary      =   job_expect.min_salary
        i.max_salary      =   job_expect.max_salary
        i.state           =   job_expect.state
        i.city            =   job_expect.city
        i.region          =   job_expect.region`

1 个答案:

答案 0 :(得分:1)

使用'related_name'可以更简单:

class Job_expectation(models.Model):
    readytoworkas  = models.OneToOneField(Readytoworkas, related_name='job_expectation')

skilllist   = Readytoworkas.objects.filter(employee_id=employee)
for i in skilllist:
    job_expect = i.job_expectation

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name