来自 Django 数据库的引用名称,而不是 id

Reference name from Django database, NOT the id

我正在发送一封包含模型中对象 ID 的电子邮件,但我想发送对象名称。

我有两个型号:

class Uniform(models.Model):
    category = models.CharField(max_length = 50)
    description = models.CharField(max_length = 50)
    price = models.FloatField(max_length = 6)
    size = models.CharField(max_length = 10)

    def __str__(self):
        return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price)

class Transaction(models.Model):
    employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT)
    uniform = models.ForeignKey(Uniform, on_delete = models.CASCADE)
    date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '{}: {} - {}'.format(self.employee_id, self.uniform, str(self.date))

和forms.py

class TransactionForm(forms.ModelForm):

    class Meta():
        model = Transaction
        fields = '__all__'

我的Views.py

def employeeCloset(request):
    form = TransactionForm()

    if request.method == 'POST':
        form = TransactionForm(request.POST)

        if form.is_valid():
            subject = 'Checked out item from Me'
            message = 'It is the responsibility of the team member to maintain all articles identified so that they are presentable and worn upon arriving according to standards required in the Employee Handbook. I understand I will be charged the deposit according to the cost identified below: \n {} \n These costs will be deducted from the team member’s paycheck and will be credited upon return of article(s). \n Any item that is not returned by the end of the pay period the cost of the item will be deducted from my paycheck. \n In order to receive full credit from items they must be returned by December 6, 2019.'.format(Uniform.__str__ == form.data['uniform'])
            from_email = settings.EMAIL_HOST_USER
            to_list = ['', settings.EMAIL_HOST_USER]
            form.save(commit = True)

            send_mail(subject, message, from_email, to_list, fail_silently=False)

            return index(request)
        else:
            print('Error form invalid')

    return render(request, 'apparelapp/employeeCloset.html', {'form':form}

.format(form.data['uniform'] 发送电子邮件项目 views.py 时,我得到统一的 ID 号 18 在电子邮件中,而不是获取整行。我想要它说的是 "Chef Coat, No Logo, 16.0, 4XL" 而不是统一的 id:

我试过引用表单 uniform 然后引用 uniform 值,但没有成功。

谢谢 Django,新手

您可以使用 id 查找整个 Uniform 对象:

uniform = Uniform.objects.get(id=int(form_data['uniform']))

然后可以参考uniform.description取名字