如何将字符串附加到django中的数据库对象

时间:2012-09-17 12:16:42

标签: python django django-models

您好我有以下代码我在feature_list = ['spa','castle','country_house','coast','golf','boutique','civil','private_hire','city','gay']中有不同的元素。在数据库中,值为1或0.所以我试图检查它们是否为1并将它们附加到新数组中。

try:
        hotel_main = models.Hotel.objects.get(slug=slug)
    except models.Hotel.DoesNotExist:
        try:
            hotel_main = models.Hotel.objects.get(id=id)
        except models.Hotel.DoesNotExist:
            raise Http404
    feature_list = ['spa','castle','country_house','coast','golf','boutique','civil','private_hire','city','gay']
    hotel_features = []
    for feature in feature_list: 
        if hotel_main.feature == 1: 
            hotel_features.append(feature)  

它给了我以下错误:' Hotel'对象没有属性'

但是在我的理解中,功能应该代表数组的字符串......请纠正我

2 个答案:

答案 0 :(得分:0)

你在做什么是错的。试试这个 -

hotel_main = models.Hotel.objects.get(slug=slug)
feature_list = ['spa','castle','country_house','coast','golf','boutique','civil','private_hire','city','gay']
hotel_features = []
for feature in feature_list: 
    if getattr(hotel_main, feature, 1):
        hotel_features.append(feature)

您正在做的事情会产生异常,因为您使用hotel_main对象动态检查列字段。我认为.功能不适用于字符串文字。因此引入了getattr

希望这会有所帮助......

答案 1 :(得分:0)

  

但是在我的理解中,功能应该代表数组的字符串......请纠正我

您是正确的,数组中的字符串已分配给feature,但您的问题是调用hotel_main.feature。 Python认为您正在寻找hotel_main对象上名为“feature”的属性。要使用当前分配给变量的内容查找属性,您应使用Python's built-in getattr function

feature_value = getattr(hotel_main, feature, 0) //default to not having the feature
if feature_value == 1:
    // the rest of your code