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- 1Please include your Notes and Blocks model.Uchenna Adubasim– Uchenna Adubasim2025-10-08 11:24:56 +00:00CommentedOct 8 at 11:24
1 Answer1
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.
Comments
Explore related questions
See similar questions with these tags.
