P
P
phisher132022-04-18 18:30:15
Django
phisher13, 2022-04-18 18:30:15

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

2 answer(s)
A
Alexander Nesterov, 2022-04-18
@AlexNest

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...

C
C0uchP0tat0, 2022-04-21
@C0uchP0tat0

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 question

Ask a Question

731 491 924 answers to any question