1

I would like to set the default category to be whatever the parent's category is set to.

Here's the basic object model right now:

class Product(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True, related_name="variants")
    category = models.ForeignKey(Category, related_name='products')

I would like to be able to do something like this:

    category = models.ForeignKey(Category, related_name='products', default=get_parent_category)

But I don't know how to go about getting the parent's category (what would that method look like?). Is there a better way to go about it?

(question is related to this one)

Community
  • 1
  • 1
bwv549
  • 5,243
  • 2
  • 23
  • 20

1 Answers1

3

Override the save method.

class Product(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True,related_name="variants")
    category = models.ForeignKey(Category, related_name='products')

def save(self, *args, **kwargs):
    if self.parent and not self.pk and not self.category:
        self.category = self.parent.category  # Could use setattr getattr too but this is easier to read imo
    return super(Product, self).save(*args, **kwargs)

If not self.pk is used so that this only happens before the model is committed to the database.

Mikeec3
  • 649
  • 3
  • 9
  • That's a beautiful solution. Marking as solved. (and just so that it is fully correct, maybe you can edit the line below the 'if' statement to be self.parent.category). Thanks!!! – bwv549 Apr 08 '15 at 22:03