Iordan Iordanov
Iordan Iordanov

Reputation: 273

Django nested serializers not returning what I want

I'm relatively new to Django and I'm working on an application that has me scratching my head. I have two models defined as follows:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    name = models.CharField(_('name'), max_length=50, blank=False)
    surname = models.CharField(_('surname'), blank=True, max_length=50)
    phone_number = models.CharField(validators=[phone_validator], max_length=16, blank=True) 


class History(models.Model):
    hist_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE
    )
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=False)
    actions = models.JSONField(default=dict)
    traces = models.JSONField(default=dict)

I would like to obtain a list of all users, and for each user I want all the History objects as a list. Here is the View I've created:

class HistoryQuery(ListAPIView):
    serializer_class = HistorySerializer

    def get_queryset(self):
        return User.objects.all()

and here is the serializer that I'm trying to use:

class HistorySerializer(serializers.Serializer):

    class HistorySummarySerializer(serializers.Serializer):

        class Meta:
            model = History
            fields = ['hist_id', 'user']

    history = HistorySummarySerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ['history']

With this setup, I'm getting an array with length equal to the number of users that I have in my database, but each of its elements is empty. I cannot figure out what I'm doing wrong, so any help is appreciated. Should I reverse my logic and query the History model instead?

If it is relevant, there are around 20k+ History entries in the database -- is it possible that Django is "lazy" and doesn't load the data? Really, any advice is much appreciated.

I should perhaps further clarify that I'd like to aggregate the History results per day for each user, but my current plan is to go one step at a time, so I'll tackle that once this part is working.

Upvotes: 0

Views: 1301

Answers (1)

user9837582
user9837582

Reputation:

Your model field isn’t what you think it is. When creating a ForeignKey relationship, if you don’t supply a related_name kwarg, Django will default it to {field_name}_set. That means if you want to get the history for a user, you’d have to do the following:

User.objects.get(pk=1).history_set.all()

Your nested serializer expects the history to live in the history field which does not exist.

Try adding source=‘history_set’ to the nested serializer field

Upvotes: 1

Related Questions