Django: NOT NULL constraint

Viewed 424

i am new to django and i get an error when I want to save a list of objects. There are two Objects Hopper (One) and Trade (Many). I am not sure how to save it in the correct way. The Hopper Object is already in the db. So i tried to set the id of the hopper as a foreigin key into the trade object.

This is the error on save the tadeArray:

django.db.utils.IntegrityError: NOT NULL constraint failed: trade.hopper_id

so that means the field is null when i try to save the trades, right?

Models (shortened):

class Trade(models.Model):
    # Relationships
    hopper = models.ForeignKey(Hopper, related_name='trades', on_delete=models.CASCADE)  # this should call the error :: django.db.utils.IntegrityError: NOT NULL constraint failed: trade.hopper_id

    # Fields
    id_db = models.IntegerField(primary_key=True, default=-1)
    # ... many attributes
    trigger_strategy = models.TextField(default=None)
    type = models.TextField(default=None)

    class Meta:
        # Set the table name.
        db_table = 'trade'

        # Set default ordering
        ordering = ['id']

        
class Hopper(models.Model):
    # Relationships
    id_db = models.IntegerField(primary_key=True, default=None)
    id = models.IntegerField(default=None)
    open_positions_count = models.TextField(default=None)
    name = models.TextField(default=None)
    exchange = models.TextField(default=None)
    hopper_id = models.TextField(default=None)
    # ... many attributes
    paper_trading = models.IntegerField(default=-1)
    start_balance = models.TextField(default=None)

Serializers:

class HopperSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hopper

        fields = ['id',
                  'open_positions_count',
                  'name',
                  'exchange',
                  'hopper_id',
                  'subscription_id',
                  # ... many attributes
                  'paper_trading',
                  'start_balance',
                  ]

    def create(self, validated_data):
        return Hopper.objects.create(**validated_data)

class TradeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Trade

        fields = [
            'id',
            'exchange',
            'currency',
            'pair',
            # ... many attributes
            'buy_id',
            'is_short',
            'result_short']
        extra_kwargs = {
            'hopper': {'allow_null': True, 'required': False}
        }

    def create(self, validated_data):
        return Trade.objects.create(**validated_data)

views.py (this def is called and throws the exeption)

@api_view(('POST', 'GET'))
@csrf_exempt
def trades(request, hopper_id):
    if request.method == 'POST':
        data = request.data
        serializer = TradeSerializer(data=data, many=True)
        if serializer.is_valid():
            hopper = Hopper.objects.get(id=hopper_id)
            print(hopper)
            serializer.save() # at this point i stuck too. the id of the hopper must be saved with the trades
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

best regards

1 Answers
class Trade(models.Model):
    
    hopper = models.ForeignKey(Hopper, related_name='trades', on_delete=models.CASCADE, null=True, blank=True)
 # ... your other fields

I have faced NOT NULL constraint failed error many times, I fixed this problem by setting my field in the above way. By setting your hopper field null=True, you are saying your database that this field may do not have any value. So the error will be removed.

Related