我已经按照站点框架的文档建议定义了多个站点。
据我所知,如果我运行应用程序的多个实例,每个实例都有不同的设置文件(不同的 SITE_ID),Django 将始终知道要使用哪个站点。
我试图做的是运行一个实例,其中有多个站点可用,并且应根据站点的当前 url 选择正确的站点。
站点文档指出:
SITE_ID 设置指定与该特定设置文件关联的站点对象的数据库 ID。如果省略该设置,get_current_site() 函数将尝试通过将域与 request.get_host() 方法中的主机名进行比较来获取当前站点。
因此,我尝试从 settings.py 中删除 SITE_ID,并希望 Django 能够检查域以找到如上所述的当前站点,但是失败并出现以下异常:
You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting or pass a request to Site.objects.get_current() to fix this error.
Run Code Online (Sandbox Code Playgroud)
所以看起来虽然文档另有说明,但这个设置是不可忽略的
我知道,当没有可用于查找当前站点的 Request 对象时,像这样使用站点框架会导致问题,但这在我的应用程序上下文中不应该是问题。
是否可以通过仅检查应用程序的当前域来使用站点框架,而无需在设置文件中对 SITE_ID 进行硬编码?
我正在使用 Django 版本 1.9.9 和 Python 3.4.3
假设我有一个可以拥有各种儿童产品的产品,模型就是这样定义的
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过滤这样的查询集?