首页 > 解决方案 > Django 模型和查询集

问题描述

我想得到你的帮助,因为我的 Django Web 应用程序被阻止了。

我的模型中有两个类:

class Document(models.Model):
    code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='')
    title = models.CharField(max_length=512, verbose_name=_('document title'))

class Download(models.Model):
    email = models.CharField(max_length=150, verbose_name=_('e-mail'), null=False)
    country = models.ForeignKey(Country, verbose_name=_('country'), related_name='download')
    doc = models.ForeignKey(Document, verbose_name=_('Document'), null=True)
    token = models.CharField(max_length=40, verbose_name=_('download token'), unique=True, null=False)
    expiration_date = models.DateTimeField(verbose_name=_('expiration date'), null=False)

如您所见DownloadDocument由于ForeignKey.

现在,在我的views.py中,我有这个:

def form_valid(self, form):
    email = form.cleaned_data['email']
    country = form.cleaned_data['country']

    for checkbox in self.request.GET.getlist('DocumentChoice'):
        document = Document.objects.get(code=checkbox)
        token = self.gen_token(email)

        now = timezone.now()
        expiration = now + settings.DOWNLOAD_VALIDITY
        Download.objects.create(email=email, country=country, doc_id=checkbox, token=token, expiration_date=expiration)

    return super(HomeView, self).form_valid(form)

我想做的事:

在这一行:Download.objects.create(email=email, country=country, doc_id=checkbox, token=token, expiration_date=expiration)

我想设置document.code = checkbox,但我没有克服找到这样做的好方法。checbox对应于document模型中的代码列表。

我试过了doc_codedoc_id_code......但我没有找到document.codedownload类中引用的好语法。

谢谢

标签: djangodjango-modelsdjango-queryset

解决方案


推荐阅读