Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i Get foreign key's value instead of id , in django rest framework

Sorry for my bad English hope u can understand what i mean.

OUT PUT IM GETTING NOW:

[
    {
        "MainCatName": 1,
        "Name": "harry potter",
        "Image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_MoxqrLp.jpg"
    },
    {
        "MainCatName": 2,
        "Name": "Princes Girl",
        "Image": "/media/character_princess_rapunzel_8320d57a.jpeg"
    },
    {
        "MainCatName": 3,
        "Name": "sex in the city",
        "Image": "/media/250px-SATC_Title.jpg"
    },
    {
        "MainCatName": 4,
        "Name": "who is dragon",
        "Image": "/media/Reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg"
    },
    {
        "MainCatName": 2,
        "Name": "drama queen",
        "Image": "/media/15241421_170761763390015_7913498865987146084_n.jpg"
    }
]

WHAT I WANT :
I WANT TO TO RETURN THE FORIGN KEY'S (MainCatName) VALUE WHICH IS IN TABLE INSTEAD OF ID. ie value in the [CategoryName = models.CharField(max_length=50)] in my models.py

LIKE

[
    {
        "MainCatName": Story Books,
        "Name": "harry potter",
        "Image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_MoxqrLp.jpg"
    },
    {
        "MainCatName": Darama,
        "Name": "Princes Girl",
        "Image": "/media/character_princess_rapunzel_8320d57a.jpeg"
    },
    {
        "MainCatName": Roamance,
        "Name": "sex in the city",
        "Image": "/media/250px-SATC_Title.jpg"
    },
    {
        "MainCatName": sex,
        "Name": "who is dragon",
        "Image": "/media/Reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg"
    },
    {
        "MainCatName": darama,
        "Name": "drama queen",
        "Image": "/media/15241421_170761763390015_7913498865987146084_n.jpg"
    }
]

Here is my code :

veiws.py :

class GETCATVeiw(APIView):
    def get(self, request):
        data = Products.objects.only('MainCatName','Name','Image')
        serializer = GETCAT(data, many=True)
        return Response(serializer.data)

    def post(self):
        pass

models.py :

class Category(models.Model):
    CategoryName = models.CharField(max_length=50)
    class Meta:
            verbose_name_plural = 'Categories'

        def __str__(self):
        return self.CategoryName

class Products(models.Model):
    MainCatName = models.ForeignKey(Category, on_delete=models.CASCADE)
    Name = models.CharField(max_length=50)
    Image = models.ImageField()
    Price = models.IntegerField()
    DiscriptionHeading = models.CharField(max_length=100)
    DiscriptionParagraph = models.TextField(max_length=1000)

    class Meta:
            verbose_name_plural = 'Products'

        def __str__(self):
            return str(self.MainCatName)+' - '+self.Name+' - '+str(self.Price)+' $'

serializers.py :

class GETCAT(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = ('MainCatName', 'Name', 'Image')

like image 295
drdree Avatar asked Sep 05 '25 03:09

drdree


2 Answers

You have the SlugRelatedField for that:

class GETCAT(serializers.ModelSerializer):
    MainCatName = serializers.SlugRelatedField(read_only=True, slug_field='CategoryName')
    class Meta:
        model = Products
        fields = ('MainCatName', 'Name', 'Image')

Edit: I'm not sure it'll work with Products.objects.only('MainCatName','Name','Image') as you'll span a database relation. Also you'll likely want to use a select_related to avoid getting N+1 DB query.

like image 186
Linovia Avatar answered Sep 08 '25 03:09

Linovia


The generic Django way is to define natural keys on your model, in this case Category:

  1. Serializing by natural key: Add a natural_key(self) method to your Category class in which you return the category's CategoryName. It has to be unique!

    def natural_key(self):
        return self.CategoryName
    
  2. Deserializing by natural key: You want to define a default manager for your Category model:

    objects = CategoryManager()
    

    and define the get_by_natural_key(self, name) method in your CategoryManager(models.Manager) class, which returns the category:

    class CategoryManager(models.Manager):
    
        def get_by_natural_key(self, name):
            return self.get(CategoryName=name)
    
like image 34
dirkgroten Avatar answered Sep 08 '25 05:09

dirkgroten