我的同事Ryan带着他的Bash脚本中的一个错误来找我,我发现了这个测试的问题:
$ mkdir ryan
$ mkdir ryan/smells-bad
$ FOO=ryan/smells-*
$ echo $FOO
ryan/smells-bad
$ touch $FOO/rotten_eggs
touch: cannot touch `ryan/smells-*/rotten_eggs': No such file or directory
Run Code Online (Sandbox Code Playgroud)
由此我推断,在echo命令期间发生了globbing,而不是在创建变量FOO时.
我们有一些解决方法,按照不正常的降序排列:
touch `echo $FOO`/rotten_eggs
Run Code Online (Sandbox Code Playgroud)
要么:
pushd
cd $FOO
touch rotten_eggs
popd
Run Code Online (Sandbox Code Playgroud)
但两者都不令人满意.我错过了一招吗?
我有像这样的多对多关系的模型:
class Contact(models.Model):
name = models.TextField()
address = models.TextField()
class Mail(models.Model):
to = models.ManyToManyField(Contact, related_name='received_mails')
cc = models.ManyToManyField(Contact, related_name='cced_mails')
Run Code Online (Sandbox Code Playgroud)
我想获取给定电子邮件的to字段或cc字段中的联系人集.我们试试吧:
>>> Contact.objects.filter(received_mails__id=111)
[<Contact: fred@foo.com>]
>>> Contact.objects.filter(cced_mails__id=111)
[<Contact: joe@bar.com>]
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.我们为每个关系都有一个联系人.但是将它们放入同一个QuerySet会很好.
>>> Contact.objects.filter(Q(received_mails__id=111) | Q(cced_mails__id=111))
[<Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, <Contact: joe@bar.com>, '...(remaining elements truncated)...']
Run Code Online (Sandbox Code Playgroud)
发生了什么?我觉得这与在SQL中连接表有关,但我真的不明白在很多关系下发生了什么.可能是我想要做的事情是愚蠢的,或者有一种简单的方法可以做到这一点.无论哪种方式,我很高兴能够走上正确的道路.
编辑:这是QuerySet的查询:
SELECT `mailshareapp_contact`.`id`, …Run Code Online (Sandbox Code Playgroud)