Django - 查询ManytoMany以获取与特定实例相关的列表

时间:2016-05-19 14:57:43

标签: django django-models django-admin django-queryset

我正在尝试计算Django Actions中作业的总成本,这标志着作业已完成,并向客户发送一封电子邮件,说明他们的车辆准备就绪。我的问题是我无法检索作业中使用的项目的成本并收到错误:

TypeError at /admin/donaldson_motors_appV2/job/
'Job' object is not iterable

方法(在admin.py内):

def job_complete(self, request, queryset):

        # Sets the date the job was complete to the time the email was sent.
        date_complete = queryset.update(date_complete=datetime.datetime.now())

        total_cost = 0
        for job in queryset:
            job_items = Item.objects.get(job)
            total_cost += job_items
            total_cost += 50
        queryset.update(total_cost=total_cost)

        # Loops all the customers selected.
        for job in queryset:
            if job.vehicle.user.user.email:
                send_mail("Donaldson Motors - Vehicle Pickup", # Subject
                          "Hello %s! Your vehicle (Registration Number: %s Manufacturer: %s Model: %s) "
                          "is ready to pick up now." % # Message
                          (job.vehicle.user.user.username, job.vehicle.reg_no,
                           job.vehicle.make, job.vehicle.model), # Wildcard fillers
                          "donaldsonmotorsproject@gmail.com", # From
                          [job.vehicle.user.user.email,]) # To

        # Notifies Staff member email has been sent
        self.message_user(request, "Vehicle is ready to pickup. User has been notified.")
    job_complete.short_description = 'Job is Complete'

型号:

class Item(models.Model):
    # Item attributes
    item_name = models.CharField(max_length=50)
    cost = models.FloatField()
    quantity = models.IntegerField()

    # One Supplier can have many Items.
    supplier = models.ForeignKey(Supplier)

    def __str__(self):
        return self.item_name


class Job(models.Model):

    # Many Item can be used in many Jobs.
    item = models.ManyToManyField(Item)
    # One Vehicle can have many Jobs.
    vehicle = models.ForeignKey(Vehicle)

    # Job attributes
    job_desc = models.TextField()
    date_booked = models.DateTimeField()
    date_complete = models.DateField(null=True, blank=True)
    total_cost = models.FloatField(null=True, blank=True)

    def __str__(self):
        return "%s, %s, %s" % (self.vehicle.reg_no, self.date_booked.time(), self.date_booked.date().isoformat())

总之,我的问题是如何访问与特定工作相关的项目列表?

1 个答案:

答案 0 :(得分:0)

您可以访问作业对象的所有项目列表,例如

items = job.item.all()