Q:

How to view advertises published by auser in his User serializer

I have user serializer in which i need to show in every user detail advertises which he published
models.py:
    class Advertise(models.Model):

    title       = models.CharField(max_length=120)
    publisher   = models.ForeignKey(User, related_name='publisher',null=True, blank=True, on_delete=models.CASCADE)
    category    = models.CharField(choices=CATEGORIES, max_length=120)
    description = models.TextField(max_length= 200, null=True, blank=True)
    image       = models.ImageField(upload_to='project_static/Advertise/img', null=True, blank=False)
    price       = models.DecimalField(decimal_places=2, max_digits=20)
    timestamp   = models.DateTimeField(auto_now_add=True)
    approved    = models.BooleanField(default=False)
    location    = models.CharField(max_length=120 , null=True, blank=True)
    contact     = models.CharField(max_length=120,null=True, blank=True)

    def __str__(self):
        """show ad name in admin page"""
        return self.title

    def get_absolute_url(self):

        return reverse("advertise:advertise-detail", kwargs={"pk":self.pk})

serilaizers.py:
class AdSerializer(serializers.HyperlinkedModelSerializer):
    publisher = serializers.ReadOnlyField(source='publisher.username')
    url       = serializers.CharField(source='get_absolute_url')

    class Meta:
        model  = Advertise
        fields = ('url','id','title','publisher','category','description','price','timestamp','approved','location','contact')
class UserSerializer(serializers.HyperlinkedModelSerializer):
    publisher = AdSerializer(source='publisher_set', many=True)
    class Meta:
        model  = User
        fields = ['id', 'username','publisher']

error:
Got AttributeError when attempting to get a value for field publisher on serializer UserSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the User instance.
Original exception text was: 'User' object has no attribute 'publisher_set'.

A:

ok, I solved it by making some changes:
class AdSerializer(serializers.HyperlinkedModelSerializer):
    publisher = serializers.ReadOnlyField(source='publisher.username')
    url = serializers.HyperlinkedIdentityField(view_name='advertise:ad_detailview', source='Advertise')

    class Meta:
        model  = Advertise
        fields = ('url','id','title','publisher','category','description','price','timestamp','approved','location','contact')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    publisher_of = AdSerializer(many=True)
    url = serializers.HyperlinkedIdentityField(view_name='advertise:user-detail', source='User')
    class Meta:
        model  = User
        fields = ('url', 'id','username', 'email', 'publisher_of')

also in models.py publisher field got related_name="publisher_of" for more symantic
This link helped
https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

