Django-style question

I have a content type issue. I am trying to get the title out of this model.

class TankProfile(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    tank_type = models.SmallIntegerField(max_length=1, choices=TANK_TYPE, db_index=True, default=1, verbose_name="Tank Type")
    ts = models.DateTimeField(auto_now=True)
    tsStart = models.DateTimeField(auto_now_add=True)
    tsEnd = models.DateTimeField(null=True, auto_now=False, blank=True)
    pic = models.CharField(max_length=25)
    slug = models.CharField(max_length=100)

    def __unicode__(self):
        return str(self.title)

    def get_title(self):
        return "%s" % self.title

      

My link model is the following which uses contenttype

class Photo(models.Model):
    album = models.ForeignKey(Album)
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType, related_name="content_type_set_for_%(class)s")
    object_pk = models.IntegerField(_('object ID'))
    server = models.CharField(max_length=20)
    dir = models.CharField(max_length=20)
    image = models.CharField(max_length=20)
    added = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=150)
    about = models.TextField()


    def get_root_title(self):

        c = ContentType.objects.get(id=self.content_type.id).model_class()
        print c.title

        return "Photos"

    def __unicode__(self):
        return str(self.id)

      

In the pattern when I call

{{ photo.get_root_title }}

Nothing appears ... and nothing is printed .. what am I doing wrong?

+1


a source to share


2 answers


Yours c

is a class object, it has no attribute title

.

What you want is an object that is referenced by both content_type

and object_id

is what is actually called a generic relationship as described in the Django docs . To use it, add FK to the class Photo

:



content_object = generic.GenericForeignKey('content_type', 'object_id')

      

then you can just use this property in your template using only {{ photo.content_object.title }}

.

+7


a source


I don't know why you specifically chose get_root_title def, but usually with django ORM, I would do it like this

{{ photo.content_type.title }}

      



and you get the title easily

0


a source







All Articles