HOW TO GET DATA FROM PARENT MODEL

63 views
Skip to first unread message

Ashutosh Mishra

unread,
Feb 25, 2021, 6:11:47 AM2/25/21
to Django REST framework
class Category(models.Model):
name = models.CharField(max_length=100,null=True,blank=True)

def __str__(self):
return str(self.name)
class Items(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category,on_delete=models.CASCADE ,related_name='items')

def __str__(self):
return str(self.name)

I have data in category model,while creating items object i want to use data from category to add category to the item
can some one tell me how to do this

Saifullah Shahen

unread,
Feb 25, 2021, 1:21:19 PM2/25/21
to Django REST framework

category = Category.object.get(pk=id)
here get the category items. 
now from that category get items like this
items = category.items.all()
items is all items of that category
Reply all
Reply to author
Forward
0 new messages