On Sat, Jan 31, 2009 at 11:01 AM, John M <retireonc...@gmail.com> wrote:

>
> Hi Karen, and thanks for the reply.
>
> I've always wanted to use the 1-1 field, but whenever a new parent
> record is added, I want it to automatically add (via the save() )
> ovoerride above to the child 1-1 table.
>
> Yes, the debug does print, and the above code seems to work from the
> shell too, it's just when I try to create a new record from the shell,
> using the above model code, it doesn't work.  I'm thinking I'm missing
> something simple?


There are two ways to fix what you have so far.  First, if you want to leave
the OneToOneField defined in hostsetting, then you will need to restructure
your unixhost save() to look more like this:

    def save(self, force_insert=False, force_update=False):
        # check if 1-1 record is needed
        need_hostsetting = self.id == None
        super(unixhost, self).save(force_insert, force_update)
        if need_hostsetting:
            # Create a hostsetting object
            print "adding hostsetting to new object"
            hs = hostsetting(host=self)
            hs.save()

That is, you need to save the new unixhost (so that it has a pk id in the
database) before you can create and save the new hostsetting that points to
it.

Alternatively, you can move the OneToOneField into the unixhost model, in
which case you'd wind up with something that looks more like this:

class hostsetting(models.Model):
    hostinfo = models.BooleanField(blank=True)
    users = models.BooleanField(blank=True)
    installed = models.BooleanField(blank=True)
    delay = models.BooleanField(blank=True)

    def __unicode__(self):
        return "Settings for host " + self.unixhost.name

class unixhost(models.Model):
    name = models.CharField(max_length=50)
    fqdn = models.CharField(max_length=50)
    os = models.CharField(max_length=10, blank=True)
    level = models.CharField(max_length=10, blank=True)
    hostsetting = models.OneToOneField(hostsetting)

    def save(self, force_insert=False, force_update=False):
        # check if 1-1 record is needed
        if self.id == None:
            # Create a hostsetting object
            print "adding hostsetting to new object"
            hs = hostsetting()
            hs.save()
            self.hostsetting = hs
        super(unixhost, self).save(force_insert, force_update)

    def __unicode__(self):
        return self.name

Karen

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to