-1

I was working on notion like app, so I have a Note(consider as a Page in notion) and in that i am having blocks, where block having different id's and held with Note in Foreign field so now in views how can i use Generics to call all those blocks under a particular note. How should i modify get_queryset()

class BlockCreate(generics.ListCreateAPIView):    serializer_class = BlockSerializer    permission_classes = [IsAuthenticated]    def perform_create(self, serializer):        #save serializer in db        if serializer.is_valid():            serializer.save()        else:            print(serializer.errors)class NoteCreate(generics.ListCreateAPIView):    serializer_class = NoteSerializer    permission_classes = [IsAuthenticated]    def perform_create(self, serializer):        if serializer.is_valid():            serializer.save()        else:            print(serializer.errors)    def get_queryset(self):        ...?

My Serializers (correct me if anything wrong)

class BlockSerializer(serializers.ModelSerializer):    class Meta:        model = Block        fields = ['id', 'text']class NoteSerializer(serializers.ModelSerializer):    blocks = BlockSerializer(many=True, read_only=True)    class Meta:        model = Notes        fields = ['id', 'header', 'user', 'blocks', 'created_at']        read_only_fields = ['created_at']    def get_blocks(self, obj):        note_blocks = obj.noteblock_set.all().order_by('order')
How should i override get_queryset() to get only blocks related to that parent note
askedOct 8 at 4:49
sbnd abhijeet's user avatar
1
  • 1
    Please include your Notes and Blocks model.CommentedOct 8 at 11:24

1 Answer1

0

I think a good way to handle this would be in yourserializers using serializer relations. Assuming in yourBlock model, you have a fieldnote which has aForeignKey relationship to theNotes model with itsrelated_name argument set toblocks, you can have a serializer like this:

class NoteSerializer(serializers.ModelSerializer):    blocks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)      class Meta:              model = Notes              fields = ['id', 'header', 'user', 'blocks', 'created_at']          ...

If your related model has a__str__ method, you can useStringRelatedField instead ofPrimaryKeyRelatedField to display it:

See theserializer relations.

answeredOct 8 at 10:33
Uchenna Adubasim's user avatar
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.