【问题标题】:Set date field reference to a field of a foreign key in Django将日期字段引用设置为 Django 中的外键字段
【发布时间】:2013-08-18 12:24:29
【问题描述】:

我有如下:

class FacturasMonthArchiveView(MonthArchiveView):
   queryset = Factura.objects.all()
   date_field = "pedido__fecha_pedido"
   make_object_list = True
   allow_future = True
   template_name = 'ventas/facturas.html'
   context_object_name = 'facturas_list'

我有一个字段pedido在表Factura 中引用了一个包含许多信息的订单,其中一个字段是fecha_pedido我想将它用于通用视图MonthArchiveView,把它放在@ 987654326@ 不起作用你怎么能看到它所以我不知道我该怎么做,有什么想法吗?

问候!

使用两个模型进行编辑:

小儿科

class Pedido(models.Model):
    referencia = models.CharField(max_length=255)
    cliente = models.ForeignKey(Cliente,related_name="cliente",on_delete=models.PROTECT)
    fecha_pedido = models.DateField()
    fecha_entrega = models.DateField()
    agencia_envio = models.ForeignKey(Envio, related_name="entrega",blank=True,null=True)
    producto = models.ManyToManyField(Producto, through='Detalle_Pedido')
    pendiente_de_factura = models.BooleanField(default=False)

    def __unicode__(self):
            return self.referencia

    def save(self, *args, **kwargs):
        super(Pedido, self).save(*args,**kwargs)

    class Meta:
        ordering = ["referencia","fecha_pedido"]

事实

class Factura(models.Model):
    iva = models.FloatField(default=0.0)
    pedido = models.ForeignKey(Pedido, related_name="pedido_factura")

    def __unicode__(self):
        return "Factura -> ",self.pedido.referencia

    def save(self, *args, **kwargs):
        super(Detalle_Pedido, self).save(*args,**kwargs)

    class Meta:
        ordering = ["pedido"]

编辑:回溯错误

Environment:


    Request Method: GET
    Request URL: http://127.0.0.1:8000/ventas/facturas/2013/8/

    Django Version: 1.5.1
    Python Version: 2.7.3
    Installed Applications:
    ('django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'widget_tweaks',
     'dajaxice',
     'dajax',
     'suit',
     'django.contrib.admin',
     'south',
     'ventas',
     'chartit')
    Installed Middleware:
    ('django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware')


    Traceback:
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      115.                         response = callback(request, *callback_args, **callback_kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
      25.                 return view_func(request, *args, **kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/base.py" in view
      68.             return self.dispatch(request, *args, **kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
      86.         return handler(request, *args, **kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/dates.py" in get
      333.         self.date_list, self.object_list, extra_context = self.get_dated_items()
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/dates.py" in get_dated_items
      509.             'previous_month': self.get_previous_month(date),
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/dates.py" in get_previous_month
      111.         return _get_next_prev(self, date, is_previous=True, period='month')
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/views/generic/dates.py" in _get_next_prev
      761.             result = getattr(qs[0], date_field)

    Exception Type: AttributeError at /ventas/facturas/2013/8/
    Exception Value: 'Factura' object has no attribute 'pedido__fecha_pedido'

【问题讨论】:

  • “不起作用”是什么意思?有什么错误,列表是空的还是什么?同时发布两个模型定义。
  • 基本上与pedido__fecha_pedido我正在尝试引用此字段以用作 date_field 但这不起作用,仅此而已,我正在使用两个模型进行编辑以澄清它.

标签: django django-views django-generic-views


【解决方案1】:

原因是_make_date_lookup_arg方法默认使用

model._meta.get_field(self.get_date_field())

要检查模型字段,这就是您可能会得到“FieldDoesNotExist”的原因。

您可以重写“_make_date_lookup_arg”方法,使视图类如下所示:

class FacturasMonthArchiveView(MonthArchiveView):
    queryset = Factura.objects.all()
    date_field = "pedido__fecha_pedido"
    make_object_list = True
    allow_future = True
    template_name = 'ventas/facturas.html'
    context_object_name = 'facturas_list'

    def _make_date_lookup_arg(self, value):
        return value

虽然我不知道这将如何影响其余代码。

【讨论】:

  • 对不起,我迟到的答案,我出去了几天,对于方法 _make_date_lookup_arg 的价值,我必须返回之前放入 date_field 的字段? pedido__fecha_pedido 在这种情况下?我真的不知道如何让它工作,我尝试了一些组合,总是说没有字段pedido__fecha_pedidofecha_pedido
  • 这就是我所说的,我希望你更新它并给我一个属性错误:'Factura' object has no attribute 'pedido__fecha_pedido'
  • @Enot 在覆盖此方法之前和之后是否会引发相同的错误?你能在某处发布整个回溯吗?
  • @Enot OK,所以我想这是不可能的,当你使用'previous_month'模板变量时,它会在内部获取日期属性,在这种情况下很难覆盖(最好不要) .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 2014-10-02
  • 2010-10-18
  • 2021-01-21
相关资源
最近更新 更多