0

I want to access every API element by URL like this "/api/v1/element_id"

I have explicitly defined the pk in serializers

serializers.py

class TweetSerializer(serializers.ModelSerializer):
    tweet_id = serializers.IntegerField()

    class Meta:
        fields = ('tweet_id', 'author', 'text', 'created_at', 'retweet_count', 'favourite_count',)
        model = Tweet

But it does not work. I get Not found error

models.py

class Tweet(models.Model):
    #tweet_id = models.ForeignKey(User, on_delete=models.CASCADE)
    tweet_id = models.IntegerField()
    created_at = models.CharField(max_length=100)
    text = models.TextField()
    author = models.CharField(max_length=100)
    retweet_count = models.IntegerField()
    favourite_count = models.IntegerField()

    def __str__(self):
        return str(self.tweet_id)

views.py


class TweetList(generics.ListCreateAPIView):
    queryset = Tweet.objects.all()
    serializer_class = TweetSerializer


class TweetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Tweet.objects.all()
    serializer_class = TweetSerializer

urls.py

urlpatterns = [
    path('<int:pk>/', TweetDetail.as_view()),
    path('', TweetList.as_view()),
]

Listing all tweets works fine, /api/v1/, but single tweet is not returned.

I have tried to set a ForeignKey in the models but then I get an error column tweet_id_id not found.

4
  • You should access the detail API by /api/v1/1234/ where 1234 is your PK of Tweet instance Commented Nov 30, 2020 at 13:45
  • Yeah I know, it does not work however Commented Nov 30, 2020 at 13:46
  • What you have got btw? Commented Nov 30, 2020 at 13:51
  • As I already stated in my question, the listing works fine, also all tweets by /api/v1/ But accessing the single element /api/v1/1234 returns Not found Commented Nov 30, 2020 at 13:53

1 Answer 1

1

You generally need to add a lookup_field to view if you wish to retrieve a particular object.

So in this scenario, your lookup_field is tweet_id

Your view becomes

class TweetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Tweet.objects.all()
    serializer_class = TweetSerializer
    lookup_field = 'tweet_id'

Then you reference same lookup_field in your url. So your url becomes

path('<tweet_id>', TweetDetail.as_view()),
Sign up to request clarification or add additional context in comments.

Comments

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.