Apologies for the oversight. When using Django Rest Framework (DRF) to construct API endpoints, you're likely not going to use print statements in your model's usage as illustrated in the previous response. Instead, you'll work with serializers and views to handle data coming in and out of your API.
Given that your question involves setting up your models for use with DRF, let's dive into how you would set up a serializer and a view to work with CustomUser and their Interests, assuming you want to expose these models via an API.
Serializers
You'll need to create serializers for your models. Here's how you can serialize both CustomUser and Interest:
from rest_framework import serializers
from .models import CustomUser, Interest
class InterestSerializer(serializers.ModelSerializer):
class Meta:
model = Interest
fields = ['id', 'name']
class CustomUserSerializer(serializers.ModelSerializer):
interests = InterestSerializer(many=True, read_only=True)
class Meta:
model = CustomUser
fields = ['id', 'username', 'telegram', 'discord', 'whatsapp', 'interests']
In the above, the CustomUserSerializer includes an interests field that demonstrates how to serialize a many-to-many relationship using DRF. We specify many=True to indicate that multiple interests can be associated with a single user, and read_only=True because we're not handling the creation of interests here.
Views
For the views, you might use DRF's generic views or viewsets to simplify CRUD operations. Here's an example using ModelViewSet, which gives you a set of CRUD operations for a model:
from rest_framework import viewsets
from .models import CustomUser, Interest
from .serializers import CustomUserSerializer, InterestSerializer
class CustomUserViewSet(viewsets.ModelViewSet):
queryset = CustomUser.objects.all()
serializer_class = CustomUserSerializer
class InterestViewSet(viewsets.ModelViewSet):
queryset = Interest.objects.all()
serializer_class = InterestSerializer
URLs
Finally, you'll need to hook up these views to URLs:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'users', views.CustomUserViewSet)
router.register(r'interests', views.InterestViewSet)
urlpatterns = [
path('', include(router.urls)),
]
With this setup, you've got a basic API for your CustomUser and Interest models, which allows for CRUD operations. This assumes you've got DRF installed and configured in your project settings.
This setup gives you endpoints for listing all users and their interests, creating new users, and managing interests. For operations like linking a user with specific interests, you might need custom methods, especially if you're dealing with updating many-to-many relationships through your API.