As default IntegerField in Django

I studied Django and ran into a little problem.

I am looking for a way to make suit_length equal to the default client height. This code works for me:

    class Customer(models.Model):
        name = models.CharField(max_length=20)
        height = models.IntegerField(default=170)

    class Suit(models.Model)
        customer = models.ForeignKey(Customer)
        suit_design = models.CharField(max_length=100)
        suit_length = models.IntegerField(default=0)
        def get_height(self):
            self.suit_length = self.customer.height
            return

But every time I create a new Suit, its default suit_length = 0, and I need to run get_height () to get what I want. Is there a default way suit_length for customer.height and avoid running get_height () every time I create a new Suit? I'm probably looking for something like this:

    class Customer(models.Model):
        name = models.CharField(max_length=20)
        height = models.IntegerField(default=170)

    class Suit(models.Model)
        customer = models.ForeignKey(Customer)
        suit_design = models.CharField(max_length=500)
        suit_length = models.IntegerField(default=lambda:self.customer.height)

But this code does not work.

+8
source share
2 answers

Django uses the save () method to actually save the data. You can rewrite it like this:

class Suit(models.Model):
    def save(self):
        if self.suit_length == 0:
            self.suit_length = self.customer.height
        super(Suit, self).save()

, .

+8

, , , .

__ init __()?

    class Suit(models.Model)
        customer = models.ForeignKey(Customer)
        suit_design = models.CharField(max_length=500)
        suit_length = models.IntegerField(default=lambda:self.customer.height)

        def __init__(self, args, kwargs):
            super(models.Model, args, kwargs)
            if kwargs['customer']:
                self.customer = kwargs['customer']
                # this creates the invariant
                self.suit_length = self.customer.height  
            else:
                raise ValueError("Must have a customer before constructing a Suit")
            # More code for suit_design, etc.
        }
0

Source: https://habr.com/ru/post/1535233/


All Articles