gpt4 book ai didi

python - Django:具有多个子模型类型的父模型

转载 作者:行者123 更新时间:2023-11-28 21:09:31 25 4
gpt4 key购买 nike

我为 CMS 创建了一组 Django 模型来显示一系列 Product

每个页面都包含一系列的行,所以我有一个通用的

class ProductRow(models.Model):
slug = models.SlugField(max_length=100, null=False, blank=False, unique=True, primary_key=True)
name = models.CharField(max_length=200,null=False,blank=False,unique=True)
active = models.BooleanField(default=True, null=False, blank=False)

然后我有一系列这个模型的 child ,用于不同类型的行:

class ProductBanner(ProductRow):
wide_image = models.ImageField(upload_to='product_images/banners/', max_length=100, null=False, blank=False)
top_heading_text = models.CharField(max_length=100, null=False, blank=False)
main_heading_text = models.CharField(max_length=200, null=False, blank=False)
...

class ProductMagazineRow(ProductRow):
title = models.CharField(max_length=50, null=False, blank=False)
show_descriptions = models.BooleanField(null=False, blank=False, default=False)
panel_1_product = models.ForeignKey(Product, related_name='+', null=False, blank=False)
panel_2_product = models.ForeignKey(Product, related_name='+', null=False, blank=False)
panel_3_product = models.ForeignKey(Product, related_name='+', null=False, blank=False)
...

class ProductTextGridRow(ProductRow):
title = models.CharField(max_length=50, null=False, blank=False)
col1_title = models.CharField(max_length=50, null=False, blank=False)
col1_product_1 = models.ForeignKey(Product, related_name='+', null=False, blank=False)
col1_product_2 = models.ForeignKey(Product, related_name='+', null=False, blank=False)
col1_product_3 = models.ForeignKey(Product, related_name='+', null=False, blank=False)
...

等等。

然后在我的 ProductPage 中有一系列 ProductRow:

class ProductPage(models.Model):
slug = models.SlugField(max_length=100, null=False, blank=False, unique=True, primary_key=True)
name = models.CharField(max_length=200, null=False, blank=False, unique=True)
title = models.CharField(max_length=80, null=False, blank=False)
description = models.CharField(max_length=80, null=False, blank=False)
row_1 = models.ForeignKey(ProductRow, related_name='+', null=False, blank=False)
row_2 = models.ForeignKey(ProductRow, related_name='+', null=True, blank=True)
row_3 = models.ForeignKey(ProductRow, related_name='+', null=True, blank=True)
row_4 = models.ForeignKey(ProductRow, related_name='+', null=True, blank=True)
row_5 = models.ForeignKey(ProductRow, related_name='+', null=True, blank=True)

我遇到的问题是,我想让 ProductPage 中的那 5 行成为 ProductRow 的任何不同子类型。但是,当我遍历它们时,例如

views.py 中:

product_page_rows = [product_page.row_1,product_page.row_2,product_page.row_3,product_page.row_4,product_page.row_5]

然后在模板中:

{% for row in product_page_rows %}
<pre>{{ row.XXXX }}</pre>
{% endfor %}

我不能将任何子字段引用为 XXXX

我尝试向父级和子级添加一个“type()”方法,以尝试区分每一行是哪个类:

class ProductRow(models.Model):

...

@classmethod
def type(cls):
return "generic"

class ProductTextGridRow(TourRow):

...

@classmethod
def type(cls):
return "text-grid"

但是如果我在模板中为 .type() 更改 XXXX 那么它会为列表中的每个项目显示 "generic" (我在数据中定义了多种行类型),所以我猜一切都作为 ProductRow 而不是适当的子类型返回。我找不到任何方法让 child 作为正确的子类型而不是父类型进行访问,或者确定它们实际上是哪种子类型(我试过 catching AttributeError 也没有帮助)。

有人可以建议我如何正确处理所有包含共同父模型的各种模型类型列表,并能够访问适当子模型类型的字段吗?

最佳答案

通常(读作“总是”)这样的东西是一个糟糕的设计:

class MyModel(models.Model):
...
row_1 = models.ForeignKey(...)
row_2 = models.ForeignKey(...)
row_3 = models.ForeignKey(...)
row_4 = models.ForeignKey(...)
row_5 = models.ForeignKey(...)

它不可扩展。如果有一天(谁知道呢?)您想要允许 6 行或 4 行而不是 5 行,您将不得不添加/删除新行并更改数据库方案(并处理具有 5 行的现有对象)。而且它不是 DRY,您的代码量取决于您处理的行数,并且涉及大量复制粘贴。

如果您想知道如果您必须处理 100 行而不是 5 行,您会怎么做,那么很明显这是一个糟糕的设计。

你必须使用 ManyToManyField()以及一些自定义逻辑,以确保至少有一行,最多有五行。

class ProductPage(models.Model):
...
rows = models.ManyToManyField(ProductRow)

如果你希望你的行被排序,你可以使用像这样的显式中间模型:

class ProductPageRow(models.Model):

class Meta:
order_with_respect_to = 'page'

row = models.ForeignKey(ProductRow)
page = models.ForeignKey(ProductPage)

class ProductPage(models.Model):
...
rows = model.ManyToManyField(ProductRow, through=ProductPageRow)

我只想允许 N 行(比方说 5),你可以实现你自己的 order_with_respect_to 逻辑:

from django.core.validators import MaxValueValidator

class ProductPageRow(models.Model):

class Meta:
unique_together = ('row', 'page', 'ordering')

MAX_ROWS = 5

row = models.ForeignKey(ProductRow)
page = models.ForeignKey(ProductPage)
ordering = models.PositiveSmallIntegerField(
validators=[
MaxValueValidator(MAX_ROWS - 1),
],
)

元组 ('row', 'page', 'ordering') 唯一性被强制执行,并且 ordering 被限制为五个值(从 0 到 4),不能超过这对 ('row', 'page') 出现 5 次。

但是,除非您有充分的理由 100% 确定没有办法以任何方式在数据库中添加超过 N 行(包括直接在您的 DBMS 控制台上输入 SQL 查询),无需将其“锁定”到此级别。

所有“不受信任”的用户很可能只能通过 HTML 表单输入来更新您的数据库。你可以使用 formsets 在填写表单时强制设置最小和最大行数。

Note: This also applies to your other models. Any bunch of fields named foobar_N, where N is an incrementing integer, betrays a very bad database design.


但是,这并不能解决您的问题。

从父模型实例取回子模型实例的最简单(读作“想到的第一个”)方法是遍历每个可能的子模型,直到获得匹配的实例。

class ProductRow(models.Model):
...
def get_actual_instance(self):
if type(self) != ProductRow:
# If it's not a ProductRow, its a child
return self
attr_name = '{}_ptr'.format(ProductRow._meta.model_name)
for possible_class in self.__subclasses__():
field_name = possible_class._meta.get_field(attr_name).related_query_name()
try:
return getattr(self, field_name)
except possible_class.DoesNotExist:
pass
# If no child found, it was a ProductRow
return self

但是每次尝试都需要访问数据库。而且它仍然不是很干。获取它的最有效方法是添加一个字段,告诉您 child 的类型:

from django.contrib.contenttypes.models import ContentType

class ProductRow(models.Model):
...
actual_type = models.ForeignKey(ContentType, editable=False)

def save(self, *args, **kwargs):
if self._state.adding:
self.actual_type = ContentType.objects.get_for_model(type(self))
super().save(*args, **kwargs)

def get_actual_instance(self):
my_info = (self._meta.app_label, self._meta.model_name)
actual_info = (self.actual_type.app_label, self.actual_type.model)
if type(self) != ProductRow or my_info == actual_info:
# If this is already the actual instance
return self
# Otherwise
attr_name = '{}_ptr_id'.format(ProductRow._meta.model_name)
return self.actual_type.get_object_for_this_type(**{
attr_name: self.pk,
})

关于python - Django:具有多个子模型类型的父模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com