Home > Back-end >  Django _id in FK Model
Django _id in FK Model

Time:11-08

I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have 2 tables, Foos and Bars.

foo_id
1
2
bar_id | foo_id (FK)
1      |1
2      |2

Bars model: foo = models.ForeignKey('Foos', on_delete=models.CASCADE)
The Django Model changes de 'foo_id' FK into 'foo' only. There is a way to keep the FK with the '_id' suffix?

CodePudding user response:

You can do this in the serializer with:

from rest_framework import serializers


class BarSerializer(serializers.ModelSerializer):
    foo_id = serializers.PrimaryKeyRelatedField(source='foo')

    class Meta:
        model = Bar
        fields = ['foo_id']

or even simply:

from rest_framework import serializers


class BarSerializer(serializers.ModelSerializer):

    class Meta:
        model = Bar
        fields = ['foo_id']

Giving the model field the name foo_id however makes no sense: if you access bar_object.foo, you get a Foo object, not the id of a Foo object, so naming it foo_id is misleading.

CodePudding user response:

I would suggest specifying the field you want to use as a FK (foos_id in your case).

models.ForeignKey(
    Foos,
    on_delete=models.CASCADE,
    to_field='id'
)

CodePudding user response:

Fixed using: foo_id = models.ForeignKey('Foos', on_delete=models.CASCADE, db_column='foo_id')

  • Related