skip to Main Content

After removing object it is still in response data.

/api/premises/premises/4

returns

{
   "detail": "Not found."
}

but /api/premises/premises/

returns

[
    {
        "id": 1,
        "image": "/product/lb-gallery-main.jpg",
        "owner": "[email protected]",
        "name": "Le Bernardin",
        "description": "Le Bernardin to francuska restauracja z owocami morza na Manhattanie w Nowym Jorku. Gilbert Le Coze i jego siostra Maguy Le Coze otworzyli restaurację w Paryżu w 1972 roku, pod nazwą Les Moines de St. Bernardin.",
        "country": "Poland",
        "city": "Gdynia",
        "postcode": "80-209",
        "address": "Starowiejska 1",
        "tags": [
            1,
            2
        ]
    },
    {
        "id": 4,
        "image": "naws.com/product/Union-Oksford.jpg",
        "owner": "[email protected]",
        "name": "dadad",
        "description": "dada",
        "country": "dada",
        "city": "dada",
        "postcode": "dad",
        "address": "dadadada",
        "tags": []
    },
    {
        "id": 2,
        "image": "196290008887877_5616210528952631689_n.jpg",
        "owner": "[email protected]",
        "name": "Sebastian Wrzałek",
        "description": "adadada",
        "country": "dadad",
        "city": "adada",
        "postcode": "dada",
        "address": "dadadadaddd",
        "tags": []
    }
]

Weird that it is not displayed on Django Admin. Also I am using Docker, after restart it is updating list and not showing deleted item. When I checked Database table directly data is correntc meaning item is removed correctly. I am thinking where it comes from and why it is cached somehow?

docker-compose.yml

version: "3"

services:
    redis:
        image: redis
        command: redis-server
        ports:
            - "6379:6397"
    app:
        build:
            context: .
        ports:
            - "8000:8000"
        volumes:
            - ./app:/app
        command: >
            sh -c "python manage.py wait_for_db &&
                   python manage.py check_connection &&
                   python manage.py migrate &&
                   python manage.py runserver 0.0.0.0:8000"
        environment:
            - DB_HOST=db
            - DB_NAME=app
            - DB_USER=postgres
            - DB_PASS=sspassword
        depends_on:
            - db
        env_file:
            - .env
    db:
        image: postgis/postgis:9.6-2.5-alpine
        environment:
            - POSTGRES_DB=app
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=sspassword

Edit.

views.py

class PremisesViewSet(viewsets.ModelViewSet):
    """Manage premises in database"""
    lookup_field = 'id'
    lookup_url_kwarg = 'premises_id'
    serializer_class = serializers.PremisesSerializer
    queryset = Premises.objects.all()
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        """Retreive the premises for auth user"""
        try:
            # TODO create wrapper for header
            if(self.request.META['HTTP_X_SOURCE_WEB']):
                return self.queryset.filter(owner=self.request.user)
        except KeyError:
            return self.queryset

    def get_serializer_class(self):
        """Return appropriate serializer class"""
        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new premises"""
        serializer.save(owner=self.request.user)

    @action(detail=True, methods=['get'])
    def menu(self, request, **kwargs):
        instance = self.get_object()
        menu = Menu.objects.filter(premises=instance, is_default=True)
        serializer = MenuProductsSerializer(menu, many=True)
        return Response(serializer.data)

Serializers.py

class PremisesSerializer(serializers.ModelSerializer):
    """Serializer a premises"""
    image = Base64ImageField(max_length=None)
    owner = serializers.ReadOnlyField(source='owner.email')
    location = serializers.HiddenField(default=Point(1,1))

    class Meta:
        model = Premises
        fields = '__all__'

        read_only_fields = ('id',)

3

Answers


  1. If you are using a browser to view /api/premises/premises/ then you may be viewing a cached version of that page. Try a Ctrl-R to reload a fresh version of the page.

    Login or Signup to reply.
  2. Maybe the issue is in the view of the endpoint /api/premises/premises/4. Can you provide more details about the view and its serializer?

    Also, I noticed that the trailing slash (/) is missing from the endpoint /api/premises/premises/4 in contrast to the endpoint /api/premises/premises/. This could trigger a redirect http call in case that the trailing slash has been defined in urls.py.

    Login or Signup to reply.
  3. The problem is in your get_queryset which is as follows:

    def get_queryset(self):
        """Retreive the premises for auth user"""
        try:
            # TODO create wrapper for header
            if(self.request.META['HTTP_X_SOURCE_WEB']):
                return self.queryset.filter(owner=self.request.user)
        except KeyError:
            return self.queryset
    

    The problem is that in the except block you are directly returning self.queryset. As the queryset is actually defined on the class it has already been evaluated in some previous request. If you see the default implementation of get_queryset has the following lines:

    if isinstance(queryset, QuerySet):
        # Ensure queryset is re-evaluated on each request.
        queryset = queryset.all()
    

    The line queryset = queryset.all() is of our concern here. What this does is (as the comment already indicates) it makes sure that the QuerySet is re-evaluated on each request. Hence you should change your implementation to:

    def get_queryset(self):
        """Retreive the premises for auth user"""
        # TODO create wrapper for header
        if self.request.META.get('HTTP_X_SOURCE_WEB') is not None: # Instead of try-except use .get() which will return `None` if the header is not set
            return self.queryset.filter(owner=self.request.user)
        return self.queryset.all()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search