如何在where子句的ecto查询中使用变量

时间:2018-09-30 11:25:18

标签: elixir ecto phoenix

我有一张地图:

import numpy as np
from PIL import Image
from sklearn.cluster import KMeans
import matplotlib.pyplot as mpimg
import matplotlib.pyplot as plt

import os

img = Image.open('Capture.png')
img_np = np.asarray(img)


pixels = img_np.reshape(img_np.shape[0] * img_np.shape[1], img_np.shape[2])

model = KMeans(n_clusters = 32)
model.fit(pixels)

pixel_centroids = model.labels_
cluster_centers = model.cluster_centers_
final = np.zeros((pixel_centroids.shape[0], 3))
for cluster_no in range(32):

    final[pixel_centroids == cluster_no] = cluster_centers[cluster_no]

comp_image = final.reshape(img_np.shape[0], img_np.shape[1], 3)
comp_image = Image.fromarray(np.uint8(comp_image))

comp_image.save('Capture_compressed.png')
img1 = mpimg.imread('Capture.png')
img2 = mpimg.imread('Capture_compressed.png')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,20))
ax1.imshow(img1)
ax1.set_title('Original image')
ax2.imshow(img2)
ax2.set_title('Compressed image')
plt.show()
print('size of original image: ', int(os.stat('Capture.png').st_size / 1024), 'kB')
print('size of compressed image:', int(os.stat('Capture_compressed.png').st_size / 1024), 'kB')

我想使用此映射进行Ecto查询,以过滤掉数据库中的某些条目。

我在想这样的事情:

  allowed_lookup = %{coordinate: "15.0", id: 1}

因此它将递归地应用map中存在的所有过滤器以获取查询集。 但是此代码无效,因为q.x未转换为q.coordinate或q.id。

1 个答案:

答案 0 :(得分:2)

尝试一下

allowed_lookup = %{coordinate: "15.0", id: 1}
Enum.reduce(allowed_lookup, Project.Models.Grid,
        fn {x,y}, query ->
            IO.puts "#{inspect x} , #{inspect y}"

            field_query = [{x, y}] #dynamic keyword list

            query|>where(^field_query)
        end)

queryset = Project.Repo.all(query)

Ecto.Query.where接受关键字列表,其中将作为键给出的字段与给定值进行比较。在这种情况下,由于字段和值是动态的,因此无法使用简单的[key: value]构造关键字列表。但是,关键字列表也可以动态构造为像[{key, value}]这样的元组列表。

 iex> [{:a, 1}] == [a: 1] # true