Home > Software design >  Load data from model in view.py Django
Load data from model in view.py Django

Time:08-20

I just started with Django and Python and I still don't understand it very well. Would it be possible to access all the information stored in Persons, showing also orderstext and archivename, I can't manage to do it :( my idea is to get all the information and save it as JSON, but I'm not getting the info from orderstext and archivename, it would be great if someone could show me the right way.

models.py

from django.db import models

class Order(models.Model):
    order_id = models.PositiveIntegerField(blank=True, null=True)
    orderstext = models.CharField(max_length=250, blank=True, null=True, )
    order_start = models.DateTimeField(blank=True, null=True)
    order_end = models.DateTimeField(blank=True, null=True)

    @property
    def default(self):
        return self.orderstext

    class Meta:
        managed = False
        db_table = 'order'



class Archives(models.Model):
    archive_id = models.AutoField(primary_key=True, null=False)
    archivename = models.CharField(max_length=50, unique=True, blank=True, null=True)
    deleted = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.archivename 

    @property
    def default(self):
        return self.archivename

    class Meta:
        managed = False
        db_table = 'archives'


class Clients(models.Model):
    name = models.CharField(max_length=20, verbose_name="Name")
    lastname = models.CharField(max_length=50, blank=True, null=True, verbose_name="Lastname")
    archives = models.ForeignKey('Archives', db_column='archive_id', on_delete=models.CASCADE, null=True, verbose_name="Archives")
    order = models.ForeignKey('Order', db_column='order_id', on_delete=models.CASCADE, null=True, verbose_name="Order")
    coments = models.CharField(max_length=250, blank=True, null=True, verbose_name="Coments")

    class Meta:
        managed = False
        db_table = 'clients'

views.py

from django.http import JsonResponse

from .models import Clients

def data_json:
    info = list(Clients.objects.all().values())
    response = {'clients': info}
    
    return JsonResponse(response)

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('clients-info/', views.data_json, name='data_json'),
]

JSON Response

{
  "clients": {
    "id": 4,
    "name": "First",
    "lastname": "Last Name",
    "archive_id": 6,
    "order_id": 3,
    "coments": "No comments"
  }
}

CodePudding user response:

You can annotate..[Django-doc] the clients queryset with the orderstext and archivename along side F-expressions..[Django-doc] like this:

from django.db.models import F

Clients.objects.annotate(
    archivename=F("archives__archivename"), 
    orderstext=F("order__orderstext"),
).values()

Although instead of using values I highly recommend using something like DRF serializers..[DRF-doc] to handle serialization of your data.

CodePudding user response:

If I'm understanding correctly, you'd want to get a certain field data on the FK field on each client object, but what you're getting is the pk value of Order and Archive models on each Client objects.

{
     "clients": {
          "id": 4,
          "name": "First",
          "lastname": "Last Name",
          "archive_id": 6,  # foreign key pk field reference
          "order_id": 3,  # foreign key pk field reference
          "coments": "No comments"
     }
}

If I'm correct, then one approach you could use is to change the reference name to reference the fields orderstext and archivename respectively instead of order_id and archive_id.

So I wouldn't change anything else but just the two foreign key fields on the Client model. Updating the reference where db_column points:

class Clients(models.Model):
     ... 
     archives = models.ForeignKey('Archives', db_column='archivename', on_delete=models.CASCADE, null=True, verbose_name="Archives")
     order = models.ForeignKey('Order', db_column='orderstext', on_delete=models.CASCADE, null=True, verbose_name="Order")
     ...

You can read more from the doc on db-column.

CodePudding user response:

There're several answers in this 12-years old question. I believe more of one might solve your problem.

Below one example of solution:

from django.http import JsonResponse
from django.core.serializers import serialize

from .models import Clients

def data_json(request):
    info = Clients.objects.all()
    response = serialize('json', info)
    
    return JsonResponse(response, safe=False)

I recommend you read the documentation about JSON request and response objects and serialization formats.

  • Related