Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get table name from Django filter objects

I have diffrent tables with same columns Like

class teachers(models.Model):
    x= models..CharField(max_length=250, blank=True, null=True);
    y= models..CharField(max_length=250, blank=True, null=True);

class students(models.Model):
    x= models..CharField(max_length=250, blank=True, null=True);
    z= models..CharField(max_length=250, blank=True, null=True);

I am using a function to process column x of both tables. So If any undesired values come in the value for x, I need to log that with the column name.

Like f = students.objects.filter()

def validate_x(obj):
    if obj.x == None:
        logger.error("None object found in table" + str(obj__tablename))
        return False
    else:
        return True

for i in f:
    validate_result = validate_x(i)

My actual scenario is not null check. I just tried to explain it with this example. Is there any way to achieve this. I am using Django 1.6

like image 985
Bamaboy Avatar asked Oct 19 '25 14:10

Bamaboy


2 Answers

object.__class__.__name__ or object._meta.object_name should give you the name of the model. (if you need model name).

when you need name of db table then you should use object._meta.db_table, as arpit-solanki said.

like image 151
pkisztelinski Avatar answered Oct 21 '25 14:10

pkisztelinski


Use this for getting database table name

obj._meta.db_table

This might be useful but in 1.11

like image 35
Arpit Solanki Avatar answered Oct 21 '25 14:10

Arpit Solanki