Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a Foreign Key Field in django rest framework?

I want to create an order, I am trying to save a milk order by a user. Basically user has to select which type of milk they want while placing an order. What should I do in my view? I am a bit confused. The following code is giving me nothing, the data is not saving. What should I do, can anyone help please?

Here are my files. models.py

MILK_CHOICES = (
('C', 'COW'),
('B', 'BUFFALO'),
('FC', 'FULL CREAM')
)

class MilkType(models.Model):
    type = models.CharField(max_length = 20, choices = MILK_CHOICES, default = MILK_CHOICES[0][1])
    quantity = models.PositiveIntegerField() # Stock
    description = models.CharField(max_length = 100)

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    milk_choice = models.ForeignKey(MilkType)
    qty = models.PositiveIntegerField(default = 1)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    orders = serializers.PrimaryKeyRelatedField(many=True, queryset=Order.objects.all())

    class Meta:
        model = CustomUser
        fields = ('id', 'username', 'email')

class MilkTypeSerializer(serializers.ModelSerializer):

    class Meta:
        model = MilkType
        fields = ('id', 'type', 'quantity', 'description')

class OrderSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source = 'user.username')

    class Meta:
        model = Order
        fields = ('id', 'user', 'milk_choice', 'qty')

views.py

class OrderList(APIView):

    def get(self, request, format = None):
        orders = Order.objects.all()
        serializer = OrderSerializer(orders, many = True)
        return Response(serializer.data)

    def post(self, request, format = None):
        serializer = OrderSerializer(data = request.data)

        if serializer.is_valid():
            serializer.save(user = request.user)
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
like image 299
Aakash Avatar asked Jun 04 '16 09:06

Aakash


People also ask

How do you save a foreign key field in Django REST Framework?

Your code is using serializer only for validation, but it is possible use it to insert or update new objects on database calling serializer. save() . To save foreign keys using django-rest-framework you must put a related field on serializer to deal with it. Use PrimaryKeyRelatedField .

How do you get a foreign key field name instead of ID in Django REST Framework?

If you want to show any field of foreign key instead of id then you can use StringRelatedField.

How do you pass extra context data to Serializers in Django REST Framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

In your OrderSerializer, define the serializer for the milk_choice field to be the MilkTypeSerializer.

class OrderSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source = 'user.username')
    milk_choice = MilkTypeSerializer()

    class Meta:
        model = Order
        fields = ('id', 'user', 'milk_choice', 'qty')
like image 128
arjunattam Avatar answered Nov 09 '22 07:11

arjunattam