django:外键和实例

django: ForeignKey and instance

我有模型

class Calendar(models.Model):
     name = models.CharField(_('name'), max_length=50)
     slug = models.SlugField(_('slug'), unique=True)

     def as_dict(self):
         return {
             'id': self.id,
             'name': self.name,
    }

class Event(models.Model):
 .....  
    title = models.CharField(_('titre'), max_length=100)      
    calendar = models.ForeignKey(Calendar, verbose_name=_('machine'))

在视图中,我有一个函数

 title= 'traction'
 macategorie= 'Atomisation'
 p = Event(title= untitre, calendar= macategorie)

我有错误:

Event.calendar must be a "Calendar" instance

如果我写

 p = Event(title= untitre, calendar_id= macategorie)

我有错误:

invalid literal for int() with base 10; 'Atomisation'

如果我写

print 'category', p.calendar_id

我显示:雾化

不清楚

如何正确书写日历?

你应该看看 django-docs

您需要先创建一个 Calendar 实例。 有点像这样:

title= 'traction'
macategorie= 'Atomisation'
moncalendar = Calendar.objects.create(name="Atomisation", slug="atomisation")
p = Event(title= title, calendar= moncalendar)

编辑 如果你想确保 Calendar 对象在 slug 中是唯一的,请尝试:

moncalendar, created = Calendar.objects.get_or_create( slug="atomisation")
moncalendar.name = "Atomisation"
moncalendar.save()

为此,您需要将模型更改为如下所示:

name = models.CharField(_('name'), max_length=50, blank=True, default="")

name = models.CharField(_('name'), max_length=50, blank=True, null=True)

or 你会把它放在一个 try-except 中并处理这种情况,在这种情况下你尝试明确添加一个具有相同 slug 的日历。 有点像这样:

try:
    moncalendar = Calendar.objects.create(name="Atomisation", slug="atomisation")
except IntegrityError:
    moncalendar = Calendar.objects.get(slug="atomisation")
    moncalendar.name = "Atomisation"  # or handle differently as you like
    moncalendar.save()

有关详细信息,请参阅 here