2

I am using django rest framework to post property_id in favorites table as a foreign key and on the basis of foreign key i want to get all fields from property table.

class Favorites(models.Model):
    """Store favorite property"""

    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    property_id = models.ForeignKey(Property, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)

Serializer:

class FavoriteSerializer(serializers.ModelSerializer):
    """Favorite Properties serializer"""

    class Meta:
        model = Favorites
        fields = ('user_id','property_id', )

Viewset:

class FavoriteViewSet(viewsets.ModelViewSet):

    http_method_names = ['get','post' ]
    serializer_class = FavoriteSerializer
    queryset = Favorites.objects.all()

Output: enter image description here

This is my first output. then i sync my property Serializer and get this one:

enter image description here

This is the output i need but it creates problem during post. During post i only need user_id and property_id but it makes my post form like this:

enter image description here

Any suggestions how i can achieve my results?

2
  • did you try raw data right from html form? Commented Oct 17, 2017 at 21:20
  • Yes i try to insert data and got error "null value in column "property_id" violates not-null constraint". Commented Oct 18, 2017 at 4:37

1 Answer 1

2

serializers.py

class FavoriteCreateSerializer(serializers.ModelSerializer):
    """Favorite Properties serializer"""

    class Meta:
        model = Favorites
        fields = ('user_id','property_id', )

class FavoriteListSerializer(serializers.ModelSerializer):
    property_id = PropertySerializer(read_only=True)

    class Meta:
        model = Favorites
        fields = ('user_id','property_id', )

views.py

class FavoriteViewSet(viewsets.ModelViewSet):

    http_method_names = ['get','post' ]
    serializer_class = FavoriteSerializer
    queryset = Favorites.objects.all()

    def get_serializer_class(self):
            if self.action == 'create':
                return FavoriteCreateSerializer
            else:
                return self.serializer_class
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Ykh this is second approach which i adopted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.