0

A very beginner question I'm sure:

I'm trying to make a dynamic table using the values from another table. Is there any way to query the database inside of models.py to build an array? This code works if I manually enter the values but I cannot find a way to query the database.

from django.db import models
import uuid
import datetime

# datalogHeaders = ["header1" , "header2"]

class keyinfo(models.Model):
    UUID = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True)
    pointKey = models.CharField(max_length=30, blank=True)
    pointID = models.CharField(max_length=30, blank=True)
    pointName = models.CharField(max_length=30, blank=True)
    address = models.CharField(max_length=30, blank=True)

datalogHeaders = keyinfo.objects.get(id=2)

class csvhistory(models.Model):
    UUID = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True)
    csvImportTimestamp = models.DateTimeField(default=datetime.datetime.now())

class datalogs(models.Model):
    dataImportTimestamp = models.DateTimeField(default=datetime.datetime.now(), primary_key=True)
    csvUUID = models.CharField(max_length=100, blank=True)
    pass

for dataHeaders in datalogHeaders:
     datalogs.add_to_class(dataHeaders, models.CharField(max_length=30, blank = True))

1 Answer 1

1

The answer is both yes and no. No because model methods are made to only work on one instance. So a method can of course return and array but will only work on one instance.

However as it's quite usual to have to work on the table instead of a singular instance, Django provides two ways to do it: custom managers and querysets.

Managers are the 'objects' part when you write

User.objects.all()

You can modify the behaviour of this objects by creating a custom manager and use it instead. This will allow you to create methods on the whole table. Custom Queryset is very similar except that it's what after the object part, and thus a allow you to do thing like :

User.objects.filter(is_superuser=True).custom_method()

There it will work on the result of the previous queryset. Even better if your method return a queryset, you can chain those.

Usually you create a custom QuerySet then a custom Manager and simply link the two so that you do both:

User.objects.custom_method()  # instead of User.objects.all().custom_method()
User.objects.filter(condition).custom_method()

The doc to implement it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.