Search code examples
djangodjango-modelsdjango-1.6

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


Solution

  • 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.