Answer the question
In order to leave comments, you need to log in
How to connect models to each other in django?
There are 2 models (User, Book), you need the user to be able to add a book to favorites.
On idea, one-to-many relation is necessary
But I not absolutely understand how to display it in the code.
Thank you)
Answer the question
In order to leave comments, you need to log in
Reading documentation is for the weak?
There you don’t even need to know English, because. there are examples.
https://docs.djangoproject.com/en/4.0/topics/db/ex...
I think the answer will be something like this
# model
class Bookmark(models.Model):
class Meta:
abstract = True
user = models.ForeignKey(User)
class BookmarkObject(Bookmark):
class Meta:
db_table = "bookmark_object"
obj = models.ForeignKey(Book ,
null=True,
on_delete=models.CASCADE)
class BookmarkView(APIView):
model = BookmarkObject
permission_classes = [IsAuthenticated]
def post(self, request, pk):
# get user
user = self.request.user.id
# get or create a bookmark
bookmark_object, created = self.model.objects.get_or_create(user=user,
obj_id=pk)
if not created:
bookmark_object.delete()
return Response(status.HTTP_201_CREATED)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question