جانغو السؤال contenttype
-
06-07-2019 - |
سؤال
ولدي مشكلة ربط نوع المحتوى. أحاول سحب لقب الخروج من هذا النموذج
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
ونموذج بلدي ربط على النحو التالي يستخدم 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)
في القالب عندما أدعو
و{{ photo.get_root_title }}
وليس هناك ما يظهر .. ويحصل على طباعة أي شيء .. ماذا أفعل الخطأ؟
المحلول
وc
الخاص بك هو كائن فئة، فإنه لا يكون لها title
السمة.
ما تريده هو كائن الذي تتم الإشارة إليه من قبل كل من content_type
وobject_id
- وهذا هو ما يسمى في الواقع <م> العلاقة العامة م>، <وأ href = "http://docs.djangoproject.com/en / ديف / المرجع / contrib / contenttypes / # ID1 "يختلط =" noreferrer "> كما هو موضح في جانغو مستندات . لاستخدامها، إضافة إلى FK الطبقة Photo
الخاص بك:
content_object = generic.GenericForeignKey('content_type', 'object_id')
وبعد ذلك يمكنك فقط استخدام هذه الخاصية في القالب الخاص بك فقط باستخدام {{ photo.content_object.title }}
.
نصائح أخرى
وأنا لا أعرف لماذا اخترت تحديدا مواطنه get_root_title ولكن عادة مع ORM جانغو وكنت تفعل ذلك مثل هذا
{{ photo.content_type.title }}
وولك بسهولة الحصول على اللقب