首页 \ 问答 \ 在不相关的Django模型上执行SQL JOIN?(Perform a SQL JOIN on Django models that are not related?)

在不相关的Django模型上执行SQL JOIN?(Perform a SQL JOIN on Django models that are not related?)

我有2个模型,用户(django.contrib.auth.models.User)和一个名为Log的模型。 两者都包含“电子邮件”字段。 Log没有指向User模型的ForeignKey。 我试图找出如何使用电子邮件字段作为通用性来对这两个表执行JOIN。

我希望能够执行基本上2个查询。 过滤的基本联接

#Get all the User objects that have related Log objects with the level parameter set to 3.
User.objects.filter(log__level=3)

我也想做一些聚合。

User.objects.all().anotate(Count('log'))

当然,能够反过来也是很好的。

log = Log.objects.get(pk=3)
log.user...

有没有办法用ORM做到这一点? 也许我可以添加到模型的Meta类来“激活”关系?

谢谢!


I have 2 Models, User (django.contrib.auth.models.User) and a model named Log. Both contain an "email" field. Log does not have a ForeignKey pointing to the User model. I'm trying to figure out how I can perform a JOIN on these two tables using the email field as the commonality.

There are basically 2 queries I want to be able to perform. A basic join for filtering

#Get all the User objects that have related Log objects with the level parameter set to 3.
User.objects.filter(log__level=3)

I'd also like to do some aggregates.

User.objects.all().anotate(Count('log'))

Of course, it would be nice to be able to do the reverse as well.

log = Log.objects.get(pk=3)
log.user...

Is there a way to do this with the ORM? Maybe something I can add to the model's Meta class to "activate" the relation?

Thanks!


原文:https://stackoverflow.com/questions/2328493
更新时间:2023-08-14 06:08

最满意答案

设置数据:

dd <- data.frame(x=c(1981,1990,2000:2013),
  y = c(3.262897,2.570096,7.098903,5.428424,6.056302,5.593942,
  10.869635,12.425793,5.601889,6.498187,6.967503,5.358961,3.519295,
  7.137202,19.121631,6.479928))

问题是指数取代大于约709的任何数都会得到一个大于最大值的数字,可以存储为双精度浮点值(大约1e308),因此会导致数值溢出。 您可以通过移动x变量轻松解决此问题:

lm(y~exp(x),data=dd) ## error
lm(y~exp(x-1981),data=dd) ## fine

但是,您可以更轻松地绘制此模型的拟合值,如下所示:

library(ggplot2); theme_set(theme_bw())
ggplot(dd,aes(x,y))+geom_point()+
   geom_smooth(method="glm",
            method.args=list(family=gaussian(link="log")))

Set up data:

dd <- data.frame(x=c(1981,1990,2000:2013),
  y = c(3.262897,2.570096,7.098903,5.428424,6.056302,5.593942,
  10.869635,12.425793,5.601889,6.498187,6.967503,5.358961,3.519295,
  7.137202,19.121631,6.479928))

The problem is that exponentiating any number larger than about 709 gives a number greater than the maximum value storeable as a double-precision floating-point value (approx. 1e308), and hence leads to a numeric overflow. You can easily remedy this by shifting your x variable:

lm(y~exp(x),data=dd) ## error
lm(y~exp(x-1981),data=dd) ## fine

However, you can plot the fitted value for this model more easily as follows:

library(ggplot2); theme_set(theme_bw())
ggplot(dd,aes(x,y))+geom_point()+
   geom_smooth(method="glm",
            method.args=list(family=gaussian(link="log")))

相关问答

更多
  • require(ggplot2) require(nlme) set.seed(101) mp <-data.frame(year=1990:2010) N <- nrow(mp) mp <- within(mp, { wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5 wow <- rnorm(N)*wav+rnorm(N)*wav^3 }) m01 ...
  • 像这样? ## simulate your dataset - could not get easyGplot2 to load.... set.seed(1) # for reproducible example weight <- data.frame(sex=c("Female","Male"), weight=rnorm(1000,mean=c(65,67),sd=1)) library(ggplot2) library(MASS) # for fitdistr(...) ge ...
  • 我在这里遇到问题时遇到了麻烦。 f <- function(x,a,b) {a * exp(b * x)} fit <- nls(y~f(x,a,b),df,start=c(a=1,b=1)) summary(fit)$coefficients # Estimate Std. Error t value Pr(>|t|) # a -0.02285668 0.03155189 -0.7244157 0.6008871 # b 0.25568987 0.19818736 1.2901422 ...
  • 这篇文章很好地解释了如何适应这样的抽象模型。 它的主旨是使用nls()来拟合“非线性最小二乘”模型: # Using the mpg data in ggplot2 library(ggplot2) # Create list of initial estimates insertList = list(a=1,b=-0.01,c=1,d=-0.01) # fit model m1 = nls(displ ~ a*exp(b*cty) + c*exp(d*cyl),data =mpg, start = in ...
  • lm与log变换y与glm与高斯错误分布和日志链接不同(至于为什么在@Lyngbakr的注释中检查链接) gz <- read.table("somet.txt") gz <- as.data.frame(gz) model_lm <- lm(log(MeanVolume) ~ DayNum, data = gz) model_glm <- glm(MeanVolume ~ DayNum, data = gz, family = gaussian(link = "log")) pred_lm <- exp( ...
  • 使用基本绘图,您需要在外部调整数据并添加它。 使用ggplot2更容易做到这一点。 例如: dat <- data.frame(x=a,y=b) library(ggplot2) ggplot(dat,aes(x=x,y=y))+ geom_point(size=5) + stat_smooth(method='glm')+ scale_y_log10() With basic plot, You need to fit your data externally and add it. Usi ...
  • 我相信,当您使用响应的自然对数变换拟合模型时,您只需要允许单独的斜率和截距适合您的分组变量Factor 。 我称之为单独的线条模型。 然后,您可以预测并获得每个Factor对数标度上的置信度(或预测)间隔,并进行反向变换以查看线条(非常类似于ggplot2原始帖子中的ggplot2 。 R中单独的线模型示例: fit1 = lm(y ~ time*Factor, data = x) summary(fit1) 该模型的输出将显示Factor的参考水平的估计截距,参考水平的估计斜率,以及参考水平和所有其他水 ...
  • 我想这就是你要找的东西: library(ggplot2) library(tidyverse) data_frame( x1=as.factor(1:3), x2=as.factor (4:6), x3=as.factor(7:9), x4=as.factor (2:7), x5=as.factor(1:6), x6=as.numeric(1:18), x7=as.numeric(18:35) ) -> mydata mydata %>% nest(-(x1: ...
  • 设置数据: dd <- data.frame(x=c(1981,1990,2000:2013), y = c(3.262897,2.570096,7.098903,5.428424,6.056302,5.593942, 10.869635,12.425793,5.601889,6.498187,6.967503,5.358961,3.519295, 7.137202,19.121631,6.479928)) 问题是指数取代大于约709的任何数都会得到一个大于最大值的数字,可以存储为双精度浮点值 ...
  • 问题是概率遵循逻辑曲线。 如果更改生日函数以返回原始成功和失败而不是概率,则可以使用适当的平滑线。 birthday<-function(n){ ntests<-1000 pop<-1:365 anydup<-function(i){ any(duplicated(sample(pop,n,replace=TRUE))) } data.frame(Dups = sapply(seq(ntests), anydup) * 1, n = n) } x<-ddply(x, .(x),f ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)