How do I get values from a linked model into an array?

Hi!
models.py:

# Подразделения
class Podraz(models.Model):
    title = models.CharField(max_length=150, verbose_name='Название подразделения', unique=True)
 
    def __str__(self):
        return self.title
 
    class Meta:
        verbose_name = 'Подразделение'
        verbose_name_plural = 'Подразделения'
        ordering = ['title', ]
 
# # Объекты
class Obct(models.Model):
    title = models.CharField(max_length=150, verbose_name='Объект', unique=True)
    podraz=models.ForeignKey(Podraz,verbose_name='Подразделение',on_delete=models.PROTECT)
    def __str__(self):
        return self.title
 
    class Meta:
        verbose_name = 'Объект'
        verbose_name_plural = 'Объекты'
        ordering = ['title', ]

Views:

def SaveObct(request):
    if request.method=='POST':
        form = ObctForm(request.POST)
        if form.is_valid():
            title = request.POST['title']
            podraz=request.POST['podraz']
            newrecord=Obct(title=title,podraz_id=podraz)
            newrecord.save()
            un=Obct.objects.values()
            unit_data=list(un)
            print(un)
            return JsonResponse({'status':'Save','unit_data':unit_data})
        else:
            return JsonResponse({'status':0})

Here is the list:

 [{'id': 26, 'title': 'Объект 1', 'podraz_id': 13}, {'id': 27, 'title': 'Объект 2', 'podraz_id': 13}, {'id': 28, 'title': 'Объект 3', 'podraz_id':
 14}]

And how can I get values from the Podraz table into the ‘unit_data’ list? For example:

[{'id': 26, 'title': 'Объект 1', 'podraz': 'Участок 1'}, {'id': 27, 'title': 'Объект 2', 'podraz':'Участок 1' }, {'id': 28, 'title': 'Объект 3', 'podraz':
 'Участок 2'}]

I need it for JsonResponse… Or is there another way?
Thanks!

The same way you access attributes from a related table anywhere else - using the “.” notation.

If you have an instance of Obct named obct, then obct.podraz is a reference to an instance of Podraz. You can then access the title in that instance as obct.podraz.title.

In this specific case, you’ve written a query to retrieve multiple instances of Obct:

What you want to do here is specify the values you want by field name:
un=Obct.objects.values('id', 'title', 'podraz.title')

Thanks! But I done it with ‘podraz__title’

1 Like