My current project is loaded with ManyToMany relationships. Most of
them are not required and default to nothing. One of them, however, is
required and there is a very clear default value I could use ... if I
could only figure out how.

Consider:

class Varietal(models.Model):
  name = models.CharField()

class Vineyard(models.Model):
  name = models.CharField()
  varietals = models.ManyToManyField(Varietal)

This site is devoted almost exclusively to Pinot Noir, so 90% of the
Vineyards are planted to Pinot Noir, but some are also planted to
Pinont Gris, Gamay Noir, etc.

1. Is it possible to express a default for a ManyToMany field? How?
Docs? Having a callable here (e.g., default=some_function) feels about
right, but the problem is that it needs to be called when we are first
creating the new object, which means it hasn't been saved yet, so it
has no id, and therefore we don't have enough info to do a
vineyard.varietals.add(<the object for Pinot Noir>)

2. Since I could not find an answer to the first question, I thought I
would make the field blank=True and then check in the Vineyard.save()
routine. If there are no varietals specified, then I would
automatically add Pinot Noir. Much to my frustration, this doesn't
seem to work.  Specifically, the following seems to do nothing at all
-- no add to the join table, no error, no nothing! Fails quietly both
for new objects and existing objects.

class Vineyard(): ...
    def save(self):
        super(Vineyard, self).save()
        if self.varietals.count() == 0:
            v = Varietal.objects.get(name="Pinot Noir")
            self.varietals.add(v)

The same logic put in a standalone script works just great.

Am I missing something really obvious?
--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to