Django:如何在shell中创建具有ManyToManyField的对象?

时间:2016-09-19 09:34:24

标签: django django-models

我认为显示代码比解释容易得多。

models.py

class Product(TimeStampedModel):
    name = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(null=True, blank=True)
    description = models.TextField(max_length=400, blank=True)
    is_active = models.BooleanField(default=True)
    place_category = models.ForeignKey(
        "PlaceCategory",
        related_name="products_by_place",  # category.products_by_place.all()
    )
    subject_category_set = models.ManyToManyField(
        "SubjectCategory",
        related_name="products_by_subject",  # category.products_by_subject.all()
    )

    objects = ProductManager()

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse(
            "products:product_detail",
            kwargs={
                "slug": self.slug,
            }
        )



class Category(TimeStampedModel):
    name = models.CharField(max_length=25, unique=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        abstract = True

    def __str__(self):
        return self.name


class PlaceCategory(Category):

    class Meta:
        verbose_name = "Place Category"
        verbose_name_plural = "Place Categories"


class SubjectCategory(Category):

    class Meta:
        verbose_name = "Subject Category"
        verbose_name_plural = "Subject Categories"

这就是我想在shell中做的事情。

# place category
self.place_category = PlaceCategory.objects.create(name="학교")

# subject category
self.subject_category1 = SubjectCategory.objects.create(name="사람")
self.subject_category2 = SubjectCategory.objects.create(name="꽃병")

# product
self.product = Product.objects.create(
    name="product name1",
    place_category=self.place_category,
    subject_category_set=(
        self.subject_category1,
        self.subject_category2,
    )
)

但它不起作用。有什么想法吗?

我能想到的是将ManyToManyFieldProduct移到SubjectCategory

但我想知道我的代码。感谢。

1 个答案:

答案 0 :(得分:1)

您需要在产品中添加主题类别。

所以这样做:

# place category
self.place_category = PlaceCategory.objects.create(name="학교")

# subject category
self.subject_category1 = SubjectCategory.objects.create(name="사람")
self.subject_category2 = SubjectCategory.objects.create(name="꽃병")

# product
self.product = Product.objects.create(
    name="product name1",
    place_category=self.place_category,
)

self.product.subject_category_set.add(self.subject_category1)
self.product.subject_category_set.add(self.subject_category2)

或者你可以做这样的事情

list_of_subject_categories = [self.subject_category1, self.subject_category2]

self.product.subject_category_set.add(*list_of_subject_categories)