简体   繁体   中英

How to auto-generate value from another entity on the same table

I have a table that has name and amount entity, and I want to happen is:

this is the sample of my table on models.py:

class Test(models.Model):
 test_id = models.IntegerField(primary_key=True)
 name = models.CharField(max_length=50)
 amount = models.IntegerField()
 timestamp = models.DateTimeField()

if entered amount is 300, the name will be 'hello', else if the entered amount is 500, the name will be 'world'. please help, been trying to figure this out since yesterday, I'm really newbie on python and django.

Create a custom save() method sth like that :

class Test(models.Model):
    test_id = models.IntegerField(primary_key=True)
    amount = models.IntegerField()
    name = models.CharField(max_length=50)
    timestamp = models.DateTimeField()
    def save(self, *args, **kwargs):
        self.name = 'hello' if self.amount == 300 else 'world'
        super(Test, self).save(*args, **kwargs)

Either you can handle this on model's custom save method or on serializer level ( ModelSerializer ) if you're using rest apis. The recommended way is to handle these kind of data manipulation in your model's serializer. Use a custom create/update method in your serializer (The logic on both solutions remains the same):

class TestSerializer(serializers.ModelSerializer):
    amount = serilaizers.IntegerField()
    name = serilaizers.CharField()

    class Meta:
        model = Test
        fields = [
            'test_id',
            'amount',
            'name',
            'timestamp',
        ]
    def create(self, validated_data):
        if validated_data['amount'] > 1200:
            validated_data['name'] = 'dry'
        elif validated_data['amount'] == 0:
            validated_data['name'] = 'wet'
        elif 900 <= validated_data['amount'] <= 1200:
            validated_data['name'] = 'light'
        elif 500 <= validated_data['amount'] < 900:
            validated_data['name'] = 'medium'
        elif 0 < validated_data['amount'] < 500:
            validated_data['name'] = 'heavy'

        return Test.objects.create(**validated_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM