Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django, what is related_name for? and how do i create shared columns to use across project?

Tags:

python

django

I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications.

My first question, is there a way to put those columns and can include them in my class each time i need them?

My second question, what is the point of the related_name attribute in the below code? without it the code will return an error, plus the value must be unique across the entire app. Is there a way to ensure its always unique?

class Poll(models.Model):
    question=models.CharField(max_length=300)
    start_poll_at=models.DateTimeField(null=True)
    end_poll_at=models.DateTimeField(null=True)
    is_active=models.BooleanField(default=True)
    created_at=models.DateField("Created at")
    created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
    updated_at=models.DateTimeField("Updated at")
    updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")


class Choice(models.Model):
    choice=models.CharField(max_length=200)
    created_at=models.DateField("Created at")
    created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
    updated_at=models.DateTimeField("Updated at")
    updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")

Thanks

like image 550
Mo J. Mughrabi Avatar asked Dec 18 '10 17:12

Mo J. Mughrabi


1 Answers

Try this:

class AbstractClass(models.Model):
    created_at=models.DateField("Created at")
    created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
    updated_at=models.DateTimeField("Updated at")
    updated_by=models.ForeignKey(User, db_column="updated_by", null=True, related_name="poll_user_updated_by")
    class Meta:
        abstract = True

And then use it as base for other models:

class Poll(AbstractClass):
    question=models.CharField(max_length=300)
    start_poll_at=models.DateTimeField(null=True)
    end_poll_at=models.DateTimeField(null=True)
    is_active=models.BooleanField(default=True)

This is the django documentation about this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes

like image 115
crodjer Avatar answered Sep 20 '22 18:09

crodjer