我正在做标签搜索功能,用户可以观察很多标签,我在一个元组中得到它,现在我想找到包含列表中至少一个标签的所有文本.
符号:text__contains__in=('asd','dsa')
我唯一的想法是做循环,例如:
q = text.objects.all()
for t in tag_tuple:
q.filter(data__contains=t)
Run Code Online (Sandbox Code Playgroud)
例如:标签输入元组,('car', 'cat', 'cinema')
输出的所有消息什么包含从元组至少一个字,所以My cat is in the car,cat is not allowed in the cinema,i will drive my car to the cinema
感谢您的帮助!
我有以下模型结构:
class Master(models.Model):
name = models.CharField(max_length=50)
mounting_height = models.DecimalField(max_digits=10,decimal_places=2)
class MLog(models.Model):
date = models.DateField(db_index=True)
time = models.TimeField(db_index=True)
sensor_reading = models.IntegerField()
m_master = models.ForeignKey(Master)
Run Code Online (Sandbox Code Playgroud)
目标是生成一个查询集,该查询集根据Master中的相关数据返回MLog中的所有字段以及计算字段(item_height)
使用Django的原始sql:
querySet = MLog.objects.raw('''
SELECT a.id,
date,
time,
sensor_reading,
mounting_height,
(sensor_reading - mounting_height) as item_height
FROM db_mlog a JOIN db_master b
ON a.m_master_id = b.id
''')
Run Code Online (Sandbox Code Playgroud)
我如何使用Django的ORM编写代码?
我有这个简单的SQL查询 -
SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid='2' GROUP BY pid;
Run Code Online (Sandbox Code Playgroud)
我如何使用Django ORM(即django模型)获得此功能.基本上我没有得到怎么办GROUP BY?
为什么第一个示例抛出TypeError (can't pickle function objects)而第二个示例没有,我想它与QuerySet评估(Django 1.4)有关?
def get_or_set_foo_cache():
if not cache.get('foo'):
foo = Foo.objects.annotate(bar_count=Count('bar')).filter(bar_count__gte=1)
print type(foo) # prints <class 'django.db.models.query.QuerySet'>
cache.set('foo', foo, 60 * 15)
return foo
return cache.get('foo')
Run Code Online (Sandbox Code Playgroud)
例2
def get_or_set_foo_cache():
if not cache.get('foo'):
foo = Foo.objects.all()
print type(foo) # prints <class 'django.db.models.query.QuerySet'>
cache.set('foo', foo, 60 * 15)
return foo
return cache.get('foo')
Run Code Online (Sandbox Code Playgroud)
如果我用列表理解设置foo它可以工作:
foo = [obj for obj in Foo.objects.annotate(bar_count=Count('bar')).filter(bar_count__gte=1)]
Run Code Online (Sandbox Code Playgroud) 我的Django select_related很奇怪
Models:
class Publisher(models.Model):
name = models.CharField(max_length=100)
class Meta:
app_label = 'models'
db_table = 'Publisher'
class Book(models.Model):
name = models.CharField(max_length=100)
publisher = models.OneToOneField(Publisher)
class Meta:
app_label = 'models'
db_table = 'Book'
Run Code Online (Sandbox Code Playgroud)
输出:
books = Book.objects.select_related('publisher').all()
print books.query
SELECT "Book"."id", "Book"."name", "Book"."publisher_id", "Publisher"."id", "Publisher"."name" FROM "Book" INNER JOIN "Publisher" ON ( "Book"."publisher_id" = "Publisher"."id" )
print books.values()
[{'publisher_id': 1, u'id': 1, 'name': u'rest framework'}]
Run Code Online (Sandbox Code Playgroud)
Django会生成正确的查询,并在我执行它时检索数据。但是值不包含发布者
现在我有一个Django查询集,我想根据另一个查询集的结果进行筛选.现在我这样做(并且它有效):
field = 'content_object__pk'
values = other_queryset.values_list(field, flat=True)
objects = queryset.filter(pk__in=values)
Run Code Online (Sandbox Code Playgroud)
其中字段是一个外键的名字pk在queryset.ORM非常智能,可以运行上面的一个查询.
我试图简化这个(即过滤对象列表自己而不是明确说pk):
field = 'content_object'
objects = queryset & other_queryset.values_list(field, flat=True)
Run Code Online (Sandbox Code Playgroud)
但是这会产生以下错误:
AssertionError: Cannot combine queries on two different base models.
Run Code Online (Sandbox Code Playgroud)
进行此类过滤的正确方法是什么?
假设我有一个可以拥有各种儿童产品的产品,模型就是这样定义的
class Country(models.Model):
name = models.CharField()
class Product(models.Model):
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children')
name = models.CharField()
countries = models.ManyToManyField(Country)
Run Code Online (Sandbox Code Playgroud)
我的目标是检索所有具有一个或多个链接到特定国家/地区的子 产品的产品.
在我的用例中,我需要将此信息作为Queryset.我试过的是这个,它的工作原理:
valid_products = []
desired_country = Country.objects.get(name='mycountry')
for product in Product.objects.all():
for child in product.children.all():
countries = child.countries.all()
for country in countries:
if country == desired_country:
valid_products.append(product.id)
desired_queryset = Product.objects.filter(pk__in=valid_products)
Run Code Online (Sandbox Code Playgroud)
此方法需要和其他查询将我的结果转换为查询集,我想避免这种情况.
是否可以直接使用Django ORM过滤这样的查询集?
我正在学习Django及其ORM数据访问方法,并且有一些我很好奇的东西.在一个特定的端点,我正在进行一些数据库调用(对Postgres) - 下面是一个示例:
projects = Project.objects\
.filter(Q(first_appointment_scheduled=True) | (Q(active=True) & Q(phase=ProjectPhase.meet.value)))\
.select_related('customer__first_name', 'customer__last_name',
'lead_designer__user__first_name', 'lead_designer__user__last_name')\
.values('id')\
.annotate(project=F('name'),
buyer=Concat(F('customer__first_name'), Value(' '), F('customer__last_name')),
designer=Concat(F('lead_designer__user__first_name'), Value(' '), F('lead_designer__user__last_name')),
created=F('created_at'),
meeting=F('first_appointment_date'))\
.order_by('id')[:QUERY_SIZE]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这不是一个小问题 - 我正在提取大量特定的相关数据并进行一些字符串操作.我比较关心性能,所以我尽我所能通过使用来提高效率,select_related()并且values()只能得到我需要的东西.
我的问题是,从概念上和广义上讲,在什么时候使用参数化SQL而不是使用ORM来编写查询变得更快(因为ORM必须首先"翻译"上面的"混乱")?我应该在什么近似的查询复杂度级别切换到原始SQL?
任何见解都会有所帮助.谢谢!
我有一张像这样的事件表
| 1 | 计划中| 2015年5月2日| 1 |
| 2 | 已交付 2015年4月2日| 2 |
| 3 | 包装好的 2015年3月2日| 3 |
| 4 | 返回| 2015年6月2日| 1 |
我想要这样的输出
| 2 | 已交付 2015年4月2日| 2 |
| 3 | 包装好的 2015年3月2日| 3 |
| 4 | 返回| 2015年6月2日| 1 |
我尝试使用query = Event.objects.annotate(order_num = Max('date')),但没有得到预期的结果。我如何实现此输出
为了方便起见,我在使用raw_sql查询,以使数据库保持最小,我正在删除多余的记录。通过此查询
#d is from a loop and has values
res=MyModel.objects.raw("DELETE FROM mydb_mymodel WHERE mydb_mymodel.s_type = '%s' and mydb_mymodel.barcode = '%s' and mydb_mymodel.shopcode = '%s' and mydb_mymodel.date = '%s'" ,[d.s_type,d.barcode,d.shopcode,d.date])
Run Code Online (Sandbox Code Playgroud)
它不是删除数据库中的记录,而是
当我这样做res.query并从postgres控制台运行它时,它将起作用!
是的,我可以使用
MyModel.objects.filter(s_type=d.s_type,barcode=d.barcode,
shopcode=d.shopcode,date=d.date).delete()
Run Code Online (Sandbox Code Playgroud)
但是我在raw_sql中缺少什么?
django ×10
django-orm ×10
python ×5
postgresql ×2
caching ×1
django-cache ×1
group-by ×1
sql ×1