5

I made a project in django, python.I would like to know Django command for knowing what's memory size of my table

user578542
  • 113
  • 4
  • 12
  • What does that even mean? What could the "memory size" of a table possibly be? The DBMS takes care of storing the data, and determines how much of that to store on disk and how much to cache in memory. Why should Django (or you) know or care? – Daniel Roseman Nov 23 '11 at 15:09

4 Answers4

8

Mixing both answers, you could calculate the size of the whole table calculating first the size of a single object of your model and then multiplying it with the number of objects you have in your table:

$ python manage.py shell

>>> import sys
>>> from myapp.models import MyModel
>>> my_model = MyModel()
>>> total_size = sys.getsizeof(my_model) * MyModel.objects.count()

This could work, but I think the right thing to do is to calculate the size of the table using the database. For example, if your using PostgreSQL, you just have to do:

SELECT pg_database_size('myapp_mymodel');

pg_database_size
------------------
         63287944
(1 row)
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
5
from django.db import connection
with connection.cursor() as c:
    c.execute("SELECT pg_size_pretty(pg_total_relation_size('my_table'))")
    c.fetchall()

e.g. >> [('7403 MB',)]

ZuLu
  • 933
  • 8
  • 17
1

do you mean database table?

for a model MyModel you can ask

MyModel.objects.count()
second
  • 28,029
  • 7
  • 75
  • 76
1

Just take a look here

sys.getsizeof(object[, default]):

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.

getsizeof calls the object’s sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

I'm not 100% sure if that's what you're looking for. Django is a Python framework, so I guess you're actually not searching for siezof in Django, but in Python itself.

Moreover, I'm not sure what will you need it for. Are you occuring some specific problem? Or do you want to know it in general?

Community
  • 1
  • 1
Gandi
  • 3,522
  • 2
  • 21
  • 31