Confused about ContentType

Suppose this is a model for the user's photo:

class Photo(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField()
    image = models.ImageField()
    pub_date = models.DateTimeFied(auto_now=True, auto_now_add=pub_date)
    update = models.DateTimeFied(auto_now=False, auto_now_add=True)

This is another model for user status:

class Status(models.Model):
        user = models.ForeignKey(User)
    tweet = models.TextFied()
    pub_date = models.DateTimeFied(auto_now=True, auto_now_add=pub_date)

Now this is a model for all user channels:

class StreamItem(models.Model):
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type','object_id')
  • In the above class , will StreamItem be an content_typeinstance data type?

  • What is object_id? Is this the instance content_typepk or the pk for the StreamItem instance?

  • How do I get an pub_dateinstance content_type(photo and state) and initialize it in an instance of StreamItem?

  • And finally, how do I display it in a template? Because I don’t know if it is text or image.

Thank.

+4
source share
1

:

1) content_type ( ), . Django , .

2) object_id

3) , content_object

stream_item.content_object.pub_date

4) , . python. , .

class Status(models.Model):
    ...
    def render_widget(self):
        return render_to_string('status_widget.html', {'status' : self })


class Photo(models.Model):
    ...
    def render_widget(self):
        return '<span>My HTML Here</span>'

:

{% for item in stream_items %}
    {{ item.content_object.render_widget }}
{% endfor %}
+1

Source: https://habr.com/ru/post/1530222/


All Articles