Patrice
Patrice

Reputation: 209

django: ForeignKey and instance

I have a model

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'))

in the view, I have a function

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

I have the error :

Event.calendar must be a "Calendar" instance

if I write

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

I have the error :

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

if I write

print 'category', p.calendar_id

I display : Atomisation

It is not clear

How to write correctly calendar ?

Upvotes: 1

Views: 151

Answers (1)

Remi Smirra
Remi Smirra

Reputation: 2539

You should have a look over the django-docs

You need to create a Calendar instance first. Somewhat like this:

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

EDIT If you want to make sure, that the Calendar object is unique by the slug, try:

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

For this to work, you would need to change your model to something like this:

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

or

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

or you would put it in an try-except and handle the case, where you try to add a Calendar with a same slug explicitly. Somehow like this:

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()

See here for more information.

Upvotes: 2

Related Questions