我正在将 PostgreSQL 与 Django 结合使用,并且尝试使用 Django ORM 从数据库中获取一些对象。
Medicine.objects.get(unique_item_id=26775)
Run Code Online (Sandbox Code Playgroud)
但是在获取时我遇到了错误 ->item_medicine.models.DoesNotExist: Medicine matching query does not exist.
然后我尝试使用 Django ORM 插入相同的内容。
Medicine.objects.create(unique_item_id=26775)
Run Code Online (Sandbox Code Playgroud)
但我再次收到错误psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key" DETAIL: Key (unique_item_id)=(26775) already exists.
在我的模型中,我添加了unique=True字段unique_item_id。
我不知道为什么会发生这种情况。我尝试了类似帖子中给出的答案,但没有任何效果。
追溯:
Traceback (most recent call last):
File "/home/rohit/virtualenvs/envmedicine/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "item_medicine_medicine_unique_item_id_key"
DETAIL: Key (unique_item_id)=(26775) already exists.
The above exception was the direct cause of the …Run Code Online (Sandbox Code Playgroud) django postgresql django-models django-orm unique-constraint
我有一个查询,我想排除空公司以及特定用户电子邮件。
Demo.objects.all().exclude(company__isnull=True, email="abc@gmail.com")
Run Code Online (Sandbox Code Playgroud)
但似乎上面的排除不适用于多个参数,我的返回查询集中有 email="abc@gmail.com" 。
如果我尝试使用单个参数进行上述查询,它会起作用。但不适用于多个参数。任何人都知道如何在 django except 中传递多个参数?
谢谢
我想编写一个查询,该查询将根据模型中的日期与现在的日期/时间的比较来添加过期注释,并根据结果接收布尔值。我找不到这是如何完成的。
到目前为止我已经尝试过以下操作:
.annotate(expired=F( F('date_updated') > datetime_now))
Run Code Online (Sandbox Code Playgroud)
有人可以让我知道实现这一目标的方法吗?
我有一个模型帖子:
class Post(models.Model):
post_title = models.CharField(max_length=120)
post_subtitle = models.TextField()
post_text = models.TextField()
vector_column = SearchVectorField(null=True)
class Meta:
indexes = (GinIndex(fields=['vector_column']),)
Run Code Online (Sandbox Code Playgroud)
我在数据库中创建了一个触发器来更新vector_column值:
create function core_post_trigger() returns trigger as $$
begin
new.vector_column :=
setweight(to_tsvector('pg_catalog.english', coalesce(new.post_title, '')), 'A') ||
setweight(to_tsvector('pg_catalog.english', coalesce(new.post_subtitle, '')), 'B') ||
setweight(to_tsvector('pg_catalog.english', coalesce(new.post_text, '')), 'C');
return new;
end
$$ language plpgsql;
create trigger vector_column_trigger
before insert or update on core_post
for each row execute procedure
core_post_trigger();
Run Code Online (Sandbox Code Playgroud)
我像这样搜索这个模型:
Post.objects.filter(vector_column=SearchQuery(query, config='english', search_type='websearch')
Run Code Online (Sandbox Code Playgroud)
尽管我在此搜索中应用了权重,但没有应用排名 ( to_tsrank)。我知道我可以在 Django 中应用排名,如下所示:
vector = …Run Code Online (Sandbox Code Playgroud) 在 django ORM 中使用 Q 过滤条件或者简单地获取未过滤的对象并在 python 中进行比较,什么会提供更好的性能。
employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data').filter(
Q(c_data__is_null=True) | Q(c_budget__gt=F('c_data__budget_spent') + offset_amt))
Run Code Online (Sandbox Code Playgroud)
电压/秒
employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data')
for employee in employee_qs:
if not employee.c_data or float(employee.budget)-employee.c_data.budget_spent > offset_amt:
#do something...
Run Code Online (Sandbox Code Playgroud)
这两个选择中哪一个的性能会更好?
我有一个网站定期从RSS提要中获取信息(好吧,目前手动,这是我的问题).目前这是作为普通的Django视图实现的,在我看来这不是很好.我想要一个使用cronjob运行的Python程序,而不是手动访问正确的URL来更新信息.
使Python程序访问我的特定Django应用程序和Django ORM的最简单方法是什么?
所以我有一些像这样的Django 1.3模型:
class Type(models.Model):
is_bulk = models.BooleanField()
class Component(models.Model):
parent = models.ForeignKey(Type)
Run Code Online (Sandbox Code Playgroud)
有些Type具有0 Component,有些具有1或2,等等。我该如何编写一个QuerySet来过滤所有具有> 0 Components的Type。即排除具有0个组件的类型?
我正在构建一个将计算机的硬件组合在一起的应用程序.这是我第一次使用django.说我有以下型号:
class Memory(models.Model):
partNum = models.CharField()
capacity = models.CharField()
class Computer(models.Model):
name = models.CharField()
memory = models.ManyToManyField(Memory)
# also has cpus, hard drives, and motherboard, but focus on memory for now
Run Code Online (Sandbox Code Playgroud)
一个内存对象可以属于许多计算机对象,一个计算机对象可以有许多内存对象 - 多对多.但是,如果使用多个计算机,计算机需要安装相同的精确记忆棒.
然而,django的manytomany字段(默认情况下?)只允许一个内存 - 计算机关系的实例,它必须是我独一无二的.有什么方法吗?
如果我在管理页面中尝试将许多相同的内存对象添加到计算机,它会说"计算机内存与此计算机和内存的关系已经存在".如果我尝试将同一个内存对象多次添加到manage.py shell中的服务器对象,则看起来只添加了一个内存对象.如果我尝试手动编辑数据库以具有重复条目,则会收到错误消息,指出该条目已存在.我看到在数据库结构中,某些"独特在一起"的索引是强制执行这一点.如果我改变了表来删除该子句,那会解决我的问题吗?除非django经理比预期的更愚蠢,否则可能不会.
我有什么选择?编写我自己的中间模型并使用through构造?但后来我不会使用酷的filter_horizontal小部件!重写我的计算机模型以获得外键字段以及内存对象数字段?但是我不会得到ManyToMany API工具.救命!
我有一份清单清单
my_list= [
[1,2,3],
[4,5,6],
...
]
Run Code Online (Sandbox Code Playgroud)
我想注释一些像这样的值:
from django.db.models import CharField, Case, When, Value
MyModel.objects.filter(...).annotate(label=Case(When(some_value__in=my_list[0] then=Value('first list')), output_field=CharField()))
Run Code Online (Sandbox Code Playgroud)
现在我需要When为其他列表添加类似的内容my_list,但my_list可能有不同的长度.
我怎么能这样做?
在添加到现有项目的新应用程序中,我遇到了一种有趣的情况。我的目标是(使用Celery任务)使用包含外键对象的带注释的聚合值的值一次更新许多行。这是我在之前的问题中使用过的一些示例模型:
class Book(models.model):
author = models.CharField()
num_pages = models.IntegerField()
num_chapters = models.IntegerField()
class UserBookRead(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
user_book_stats = models.ForeignKey(UserBookStats)
book = models.ForeignKey(Book)
complete = models.BooleanField(default=False)
pages_read = models.IntegerField()
class UserBookStats(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
total_pages_read = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)
我正在尝试:
post_save来自Book实例的信号来更新pages_read相关UserBookRead对象Book。pages_read每个UserBookRead已更新的任务,并更新total_pages_read每个相关的任务UserBookStats(这是发生问题的地方)我正在尝试尽可能地减少查询的数量-步骤1已经完成,并且只需要对我的实际用例进行少量查询,只要适当地优化了这些查询,这对于信号处理程序似乎是可接受的。
步骤2涉及更多,因此委派给后台任务。我已经设法以一种非常干净的方式完成了大部分任务(至少对我而言)。
我遇到的问题是,当UserBookStats使用total_pages聚合(Sum()所有pages_read相关UserBookRead对象的全部)注释查询集时,我不能直接update使用查询集来设置total_pages_read字段。
这是代码(Book实例作为传递给任务book): …