温馨提示:本文翻译自stackoverflow.com,查看原文请点击:django - Filtering Conditions in Python Serializer

django - Python序列化程序中的过滤条件

发布于 2020-03-28 23:42:33

我正在尝试使用序列化程序来获取与模型中的布尔条件匹配的模型中的所有场所。我想获得所有符合条件的场地,即“已赞助”。这是我到目前为止的内容:

模型

class Venue(models.Model):
    venue_name = models.CharField(max_length=500, blank=False)
    venue_photo = models.ImageField(upload_to= ‘venue_photo/', blank=False, default='')
    venue_logo = models.ImageField(upload_to= ‘venue_logo/', blank=False, default='')
    description = models.CharField(max_length=250, blank=True)
    phone = models.CharField(max_length=500, blank=True)
    ratings = models.FloatField(default="0.0", blank=True)
    sponsored_venue = models.BooleanField(default=False)
    signup = models.DateTimeField(default = timezone.now)
    last_signin = models.DateTimeField(default = timezone.now)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘venue')

序列化器

class VenueSerializer(serializers.ModelSerializer):
    venue_logo = serializers.SerializerMethodField()
    venue_photo = serializers.SerializerMethodField()

    opening_hours = OpeningHoursSerializer(
        many=True, source='openinghours_set', read_only=True)

# shows these fields from each venue signed up
    def get_venue_logo(self, venue):
        request = self.context.get('request')
        venue_logo_url = venue.venue_logo.url
        if venue_logo_url:
            return request.build_absolute_uri(venue_logo_url)
        return ""
    def get_venue_photo(self, venue):
        request = self.context.get('request')
        venue_photo_url = venue.venue_photo.url
        if venue_photo_url:
            return request.build_absolute_uri(venue_photo_url)
        return ""
    class Meta:
        model = venue
        fields = ("id", "venue_name", "phone", "street_address", "venue_logo", "venue_photo",
                  "street_address", "city", "state", "zip_Code", "lat", "lng", 'latlng', 'opening_hours', "ratings")

查看更多

查看更多

提问者
A True Novice
被浏览
16
Arakkal Abu 2020-01-31 18:01

序列化程序仅负责您提供的数据序列化过程您可以从调用序列化程序的位置(可能是从视图)控制Model QuerySet

像这样

qs = Venue.objects.filter(sponsored_venue=True)
serializer = VenueSerializer(qs, many=True)
serialzed_data= serializer.data 

发布
问题

分享
好友

手机
浏览

扫码手机浏览