Hello everyone, I’m a Django newbie so I’m sorry if this question has already been asked.
I tried to find an answer to my doubts, but I couldn’t.
I have two models:
#users/models.py
class CustomUser(AbstractUser):
username = models.CharField(max_length=255, unique=True)
email = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
favorites = models.ManyToManyField(Activities)
#activities/models.py
class ActivityTypes(IntEnum):
LEISURE = 0
PHYSICAL = 1
MENTAL = 2
SOCIAL = 3
@classmethod
def choices(cls):
return [(key.value, key.name) for key in cls]
class Activities(models.Model):
name = models.CharField(max_length=255, unique=True)
type = models.IntegerField(choices=ActivityTypes.choices(), default=ActivityTypes.LEISURE)
solo = models.BooleanField(default=False)
And these are the serializers:
#users/serializers.py
class UserSerializer(serializers.ModelSerializer):
favorites = ActivitiesSerializer(many=True, read_only=True)
class Meta:
model = CustomUser
fields = ['id', 'username', 'email', 'password', 'favorites']
extra_kwargs = {
'password': {'write_only': True}
}
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
#activities/serializers.py
class ActivitiesSerializer(serializers.ModelSerializer):
class Meta:
model = Activities
fields = ('id', 'name', 'type', 'solo')
I’m trying to write a view to basically retrieve the activities of a certain type and the users that have those activities as favorites and return this result in JSON.
In sql it would be something like this (assuming that the through table is called Favorites):
select Activities.name, Activities.type, CustomUser.username, CustomUser.email
from Activities join Favorites on Activities.id = Favorites.activity
join CustomUser on Favorites.user = CustomUser.id
where type = "...";
By the way, I run this same query (adapted obviously) on the sqlite database I’m using and it returns exactly the data I need, so I would say that the models are somehow correct.
As you can assume, I’m not having much success in writing such query in Django.
I’m not even sure that my serializers are right for the job.
I was able to retrieve the users and their favorite activities, like so:
users = CustomUser.objects.exclude(favorites=None).prefetch_related('favorites')
serializer = UserSerializer(users, many=True)
return JsonResponse(serializer.data, safe=False)
but not the other way around (the activities and the users that have them as favorites).
So, how can I solve my problem?
Thanks in advance to anyone who will answer!