创建新对象返回无值字段

2022-01-19 00:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的模型创建一个新对象,但是继续为一个字段获取值none。你知道吗

我的模型是这样的:

class KeyCategory(models.Model):
    program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE)
    name = models.CharField('Name', max_length=100)
    events = models.ManyToManyField('Event', through='EventQuota')

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
        ordering = ['name']
        unique_together = ("program", "name")
        permissions = (
            ('view_key_category', 'Have access to categories'),
        )


class EventQuota(models.Model):
    key_category = models.ForeignKey(KeyCategory, on_delete=models.CASCADE, related_name='key_quota')
    event = models.ForeignKey('Event', on_delete=models.CASCADE, related_name='key_quota')
    quota = models.PositiveIntegerField('Quota', default=0)

    class Meta:
        verbose_name = 'Quota'
        verbose_name_plural = 'Quotas'
        unique_together = ('key_category', 'event')

当我现在尝试创建KeyCategory和EventQuota时,KeyCategory的字段“events”总是返回core.Event.None

        if program.pk == 1:
            for _ in range(0, 2):
                key_category = KeyCategory(
                    program=program,
                    name=random.choice(self.eventList)
                )
                key_category.save()
                event_quota = EventQuota(
                    key_category=key_category,
                    event = random.choice(eventList),
                    quota = random.randint(0,100)
                )
                event_quota.save()

注意:random.choice中的eventList是对象的查询集列表。你知道吗

我试着以DjangosExtra fields on Many-to-Many relationships为例,但不知怎么的,我似乎遗漏了一些东西,或者做了一些不正确的事情?如果有任何帮助,我将不胜感激!谢谢你的关心。你知道吗

日志记录:

import logging
logger = logging.getLogger(__name__)
logger.debug(key_category.events)