通过mixins使用自定义的条来处理重复的对象

时间:2019-03-06 18:33:41

标签: django django-models django-views django-urls slug

我们有一个django应用,其中包含两个对象:城市和事件。对于我们来说,常见的网址格式是:

app.com/city/name-of-city/event/name-of-event,其中name-of-cityname-of-event是。例如:

class City(models.Model):
      name = models.CharField(max_length=100, unique=True)
      slug = AutoSlugField(populate_from='name', always_update=True, unique=True, sep='-', max_length=255)
      ...

事件在事件模型上以相同的方式获得提示:

slug = AutoSlugField(populate_from='name', always_update=True, unique_with='city', sep='-', max_length=255)

我很难解决的问题是如何处理一个实例,其中一个城市有多个具有相同名称的事件。

mixins.py

class CityMixin(object):
    city_slug_url_kwarg = 'slug'
    city = None

    def fetch_city(self, request, *args, **kwargs):
        if not self.city:
            self.city = get_object_or_404(
                City, slug=kwargs.get(self.city_slug_url_kwarg))
        return self.city

    def get_context_data(self, **kwargs):
        kwargs.setdefault('city', self.city)
        return super(CityMixin, self).get_context_data(**kwargs)

    def dispatch(self, request, *args, **kwargs):
        """
        Sets 'city' within the view
        """
        self.city = self.fetch_city(request, *args, **kwargs)
        return super(CityMixin, self).dispatch(request, *args, **kwargs)


class EventMixin(CityMixin):
    city_slug_url_kwarg = 'city_slug'
    event_slug_url_kwarg = 'slug'
    event = None

    def fetch_event(self, request, *args, **kwargs):

        if not self.event:
            event = get_list_or_404(
                Event, slug=kwargs.get(self.event_slug_url_kwarg))

        return self.event

    def dispatch(self, request, *args, **kwargs):
        """
        Sets 'city' and 'event' within the view
        """
        user = request.user
        self.city = self.fetch_city(request, *args, **kwargs)
        self.event = self.fetch_event(request, *args, **kwargs)
        if self.event.city != self.city:
            raise Http404

        return super(EventMixin, self).dispatch(request, *args, **kwargs)

如果我请求以下活动:

event = get_object_or_404(Event, slug=kwargs.get(self.event_slug_url_kwarg))

如果存在多个同名事件,它将抛出err(MultipleObjectsReturned)。

如果我请求以下活动:

event = get_list_or_404(Event, slug=kwargs.get(self.event_slug_url_kwarg))

并且有相同的事件,应用程序不知道列表中的哪个obj或索引是正确的obj。

有没有一种方法可以确保请求正确的obj,它也可以处理重复的事件名称情况?

谢谢

1 个答案:

答案 0 :(得分:1)

这些子弹在每个城市将始终是唯一的,因为您已经设置了unique_with属性。但是您没有在查询中使用城市,因此您将获得所有城市的事件-可以使用相同的子弹。您需要在查询中使用城市:

event = get_list_or_404(
    Event,
    slug=kwargs.get(self.event_slug_url_kwarg),
    city__slug=kwargs.get(self.city_slug_url_kwarg)
)