在与多个外键关联的视图中接收对象。 Django,Python

时间:2019-02-03 12:39:09

标签: python django django-queryset

我正在尝试从我的models.py文件中的一个类中获取值,该类由多个中间外键绑定。如下图所示。

class Masseurs(models.Model):
    user = models.CharField(max_length=10) #element do zamiany na unikalna nazwe uzytkownika
    name = models.CharField(max_length=70)
    description = models.CharField(max_length=400)
    supply = MultiSelectField(choices=CUSTOMER_ACCESS)
    payment_method = MultiSelectField(choices=PAYMENT_METHODS)
    deliver = models.IntegerField()
    sex = models.CharField(max_length=1, choices=SEX_MASSEURS)

    def average_rating(self):
        all_ratings = [list(map(lambda x: x.rating, self.review_set.all()))]
        return np.mean(all_ratings)

    def __str__(self):
        return self.user

# these are the days of the week of the year
class WorkTime(models.Model):
    week_of_year = models.CharField(max_length=20)
    masseurs = models.ForeignKey(Masseurs, on_delete=models.CASCADE)

    def __str__(self):
        return self.week_of_year

# these are single days
class DayTime(models.Model):
    day_of_week = models.ForeignKey(WorkTime, on_delete=models.CASCADE)
    day_name = models.CharField(max_length=30)
    full_time = models.BooleanField(default=None)

    def __str__(self):
        return self.day_name

# these are individual time units such as ('from 8.00-9.00')
class Time(models.Model):
    day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE)
    compartment = models.CharField(max_length=11)

    def __str__(self):
        return self.compartment

现在在我的view.py中,使用get_object_or_404从“ Masseurs”表中获取一个对象,如下图所示。

views.py

def masseur_detail(request, masseurs_id):
    masseur = get_object_or_404(Masseurs, pk=masseurs_id)
    daytime = Time.objects.select_related('day_time__day_of_week__masseurs').get(id=masseurs_id)
    context = {'masseur': masseur, 'daytime': daytime}
    return render(request, 'masseur/masseur_detail.html', context)

然后,使用“白天”,我尝试获取特定按摩师的所有工作时间。但是,他收到错误消息“不存在时间匹配查询。”

templates.html

{% for time in daytime.time_set.all %}
<span class="badge badge-lg badge-pill badge-success text-uppercase">11.00- 
  12.00</span>
{% endfor %}

如何从'DayTime'表中获取所有值,这些表通过许多外键链接到模板中刚呈现的单个'Masseurs'。

1 个答案:

答案 0 :(得分:1)

我认为您对时间的查询错误。我会做这样的事情:

首先,更新相关名称:

class Time(models.Model):
    # rest of the fields
    day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE, related_name='times')

然后,我们需要在白天使用select_related来代替prefetch related,因为我们正在通过反向关系来获取相关对象:

day_time = DayTime.objects.prefetch_related('times').get(day_of_week__masseurs_id=masseurs_id)

与预取相关的优点是,它将为该Time对象获取相关的DayTime实例。因此,我们不需要对数据库进行额外的查询。

现在我们可以在模板中使用它:

{% for time in daytime.times.all %}  // updated here
<span class="badge badge-lg badge-pill badge-success text-uppercase">11.00- 
  12.00</span>
{% endfor %}

OR

直接这样查询:

times = Time.objects.filter(day_time__day_of_week__masseurs_id=masseurs_id)