Django继承的模型:“无法将关键字'keyword'解析为字段。” (Django 2.1.1)

时间:2018-09-06 15:20:39

标签: django model django-queryset inherited

伙计们。相同的上下文处理器,新问题(链接到this question)。

我使用以下模型来检查网站上的促销活动:

class PagePromotion(LinkedPromotion):
   """
   A promotion embedded on a particular page.
   """
   page_url = URLField(max_length=128, min_length=0)

   def __str__(self):
       return "%s on %s" % (self.content_object, self.page_url)

   def get_link(self):
       return reverse('promotions:page-click',
                   kwargs={'page_promotion_id': self.id})

   class Meta(LinkedPromotion.Meta):
       verbose_name = _("Page Promotion")
       verbose_name_plural = _("Page Promotions")

那是从该模型继承的:

class LinkedPromotion(models.Model):

# We use generic foreign key to link to a promotion model
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = fields.GenericForeignKey('content_type', 'object_id')

position = models.CharField(_("Position"), max_length=100,
                            help_text="Position on page")
display_order = models.PositiveIntegerField(_("Display Order"), default=0)
clicks = models.PositiveIntegerField(_("Clicks"), default=0)
date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)

class Meta:
    abstract = True
    app_label = 'promotions'
    ordering = ['-clicks']
    verbose_name = _("Linked Promotion")
    verbose_name_plural = _("Linked Promotions")

def record_click(self):
    self.clicks += 1
    self.save()
record_click.alters_data = True

在与此页面相关的上下文处理器上,我编写了代码来请求页面提升,例如:

def get_request_promotions(request):
"""
Return promotions relevant to this request
"""

promotions = PagePromotion.objects.filter(page_url=request.path).order_by('display_order')

if 'q' in request.GET:
    keyword_promotions \
        = KeywordPromotion.objects.select_related().filter(keyword=request.GET['q'])
    if keyword_promotions.exists():
        promotions = list(chain(promotions, keyword_promotions))
return promotions

起初它就像链接的版本,但是由于遇到以下错误,我尝试对其进行修改:

Cannot resolve keyword 'page_url' into field.
Choices are: clicks, content_object, content_type, content_type_id, 
date_created, display_order, id, object_id, position`

如果转到上一个问题,您将看到两个代码之间的细微差别。问题似乎是Django无法识别与继承的模型相关联的字段,但是我不知道为什么。有提示吗?

1 个答案:

答案 0 :(得分:0)

我还没有完全解决这个问题,但是问题似乎出在URLField上。不知道Django是否无法理解该字段,但是当我将字段更改为CharField时,问题就解决了。我将在要求URLField的字段上插入一个验证器,但是如果有人遇到类似的问题,那是解决它的一种方法。