-2

我有一个方法:

 def get_netmask(user=None):
     user = User.objects.get(username=user)
     id_user = user.id
     obj = Host.objects.get(user=id_user)
     obj = obj.ipv4_sub_net.distinct('ipv4_sub_net').order_by('ipv4_sub_net')

     # In this line i am getting an error: `'unicode' object has no
     # attribute 'distinct'` but the query is not complete . For full
     # question please follow the lines and given example

     return obj

Host 模型的对象是ipv4_sub_netipv6_sub_net。我定义上述方法的动机是从 ipv4_sub_net+ipv6_sub_net模型字段中获取值,该字段将从Host model对应于请求用户(登录用户)中获取。为此,我在调用它时传递reuest.user.usernameget_netmask参数。ipv4_sub_net除此之外,我还想ipv6_sub_net单独返回 count os 类似的条目。

例如:在表中有四个列存在:

id      user_id        ipv4_sub_net       ipv6_sub_net
1       2              1.0.0.1             /23
2       2              8.9.7.3             /23
3       1              23.2.3.4            /43
4       2              1.0.0.1             /23

所以,假设请求用户是user_id 2. 因此,根据方法定义,它将返回字典。字典的第一个索引包含唯一IPv4_sub_net + ipv6_sub_net的,"1.0.0.1"并且第二个索引将返回为 ipv4的sub_net 2为ipv6/23的返回相似的计数。sub_netipv4 and the third index will return the count of similarfor ipv6 whichand

4

1 回答 1

1

尝试改变

obj = obj.ipv4_sub_net.distinct('ipv4_sub_net').order_by('ipv4_sub_net')

obj = obj.distinct('ipv4_sub_net').order_by('ipv4_sub_net')

编辑

在第一次通过时,我错过了另一个错误。你也应该改变

obj = Host.objects.get(user=id_user)

obj = Host.objects.filter(user=id_user)

get如果返回多个对象,将始终返回单个对象并引发错误。如果您期待一个对象,那么我不确定您要做什么。

于 2012-05-26T22:22:11.090 回答