创建新对象将返回无值的字段

时间:2018-12-02 19:13:16

标签: python django many-to-many

我正在尝试创建模型的新对象,但要在一个字段中始终获取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的“事件”字段始终返回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()

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

我尝试遵循Djangos Extra fields on Many-to-Many relationships的示例,但是似乎某种程度上我在这里丢失了某些东西,或者做的方法不正确?将不胜感激!谢谢。

记录:

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

1 个答案:

答案 0 :(得分:1)

当您访问key_category.events时,您正在询问字段的值(或外键字段的单个对象)。但是,对于ManyToMany关系而言,您需要多个对象(一个查询集)。 使用key_category.events.all()返回与key_category相关的对象,而不仅仅是单个值。

export default class OrderTopMenu extends Component {
   constructor(props) {
   super(props);
    console.log(this.props.args);
    console.log(this.props.args2);

    this.state = {
      orderInfo: this.props.args.orderInfo,
      statuses: [],
      messages: [],
      contacts: [],
      chosenContacts: [],
      files: [],
      chosenFiles: [],
      message: '',
      message_target: '',
      status_id: args.status_id,
      ins_order: this.props.args.ins_order,
      ins_type:  this.props.args.ins_type,
      lack_claims_status: this.props.args.lack_claims_status,
      readonly: true,
      target_to_send: '',
      files_required: false,
      messageChosen: false,
      auth_user: this.props.args2,
      policies: {
          comprehensive_policy_number: '',
          compulsory_policy_number: '',
      }
  }

}