0

I am using Python 2.7 and Django 1.6.3 I want to define extra model field which is not actually in db table. I have a way which is defining a callable method with property annotation like;

class MyClass(models.Model):
    my_field = models.CharField(max_length=50)

    @property
    def my_extra_field(self):
        return self.my_field+'extra value'

This works fine to show it on admin change list pages. But the extra field is not on db level. It is being generated on programming level. Django asks it for every model object.

This cause me some troubles. My all admin change list pages have capability of exporting as excel or some other type. I am using admin query set to build that report. I have also jasper reports mechanism that works with SQL select queries. So, I, want to use the queryset to take this select query.

I think being able to define extra fields on db level is important for something. Not just for reason of mine. So, the question all about this.

Is there a way to define an extra custom fields on db level instead of programming level in Django.

Thank you!.

Edited

Adding it to admin list_filter is also another problem if it is not really a field. Django does not allow you to add it.

1 Answer 1

1

Could you create a new database field and then overwrite the save method to populate that field? I do that often to create a marked up version of a text field. For example:

class Dummmy(models.Model):
    content = models.TextField()
    content_html = models.TextField(editable=False, null=True)

    def save(self, *args, **kwargs):
        self.content_html = markdown(self.content)
        super(Dummmy, self).save(*args, **kwargs)

So for you:

class MyClass(models.Model):
    my_field = models.CharField(max_length=50)
    my_extra_field = models.CharField(editable=False, null=True)

    def save(self, *args, **kwargs):
        self.my_extra_field = self.my_field + 'extra value'
        super(MyClass, self).save(*args, **kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

This will cause redundant data duplication, but this is really better way I could find until we find another way which does not cause data duplication. I mean, there could be a better way that select on existing db column. So, I want to wait for a while. Maybe we can have better way. Thank you for your answer

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.