多对多关系。ORM Djang公司

2024-04-28 05:12:11 发布

您现在位置:Python中文网/ 问答频道 /正文

class Toy(models.Model):
    name = models.CharField(max_length=20)
    desc = models.TextField()

class Box(models.Model):
    name = models.CharField(max_length=20)
    proprietor = models.ForeignKey(User, related_name='User_Box')
    toys = models.ManyToManyField(Toy, blank=True)

如何创建将玩具添加到框中的视图?

def add_this_toy_to_box(request, toy_id):

Tags: nameboxmodelmodelslengthdescmaxclass
2条回答

您可以使用Django的^{}

A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases:

The “other side” of a ForeignKey relation. That is:

class Reporter(models.Model):
    ...

class Article(models.Model):
    reporter = models.ForeignKey(Reporter)

In the above example, the methods below will be available on the manager reporter.article_set.

Both sides of a ManyToManyField relation:

class Topping(models.Model):
    ...

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping)

In this example, the methods below will be available both on topping.pizza_set and on pizza.toppings.

这些相关经理有一些额外的方法:

  1. 若要创建新对象,请将其保存并放入相关对象集中。返回新创建的对象: 创建(**kwargs)

    >>> b = Toy.objects.get(id=1)
    >>> e = b.box_set.create(
    ...     name='Hi',
    ... )
    
    # No need to call e.save() at this point -- it's already been saved.
    
    # OR:
    
    >>> b = Toy.objects.get(id=1)
    >>> e = Box(
    ...     toy=b,
    ...     name='Hi',
    ... )
    >>> e.save(force_insert=True)
    
  2. 要将模型对象添加到相关对象集,请执行以下操作:

    add(obj1[, obj2, ...])
    

    示例:

    >>> t = Toy.objects.get(id=1)
    >>> b = Box.objects.get(id=234)
    >>> t.box_set.add(b) # Associates Box b with Toy t.
    
  3. 要从相关对象集中删除指定的模型对象,请执行以下操作:

    remove(obj1[, obj2, ...])
    
    >>> b = Toy.objects.get(id=1)
    >>> e = Box.objects.get(id=234)
    >>> b.box_set.remove(e) # Disassociates Entry e from Blog b.
    

    In order to prevent database inconsistency, this method only exists on ForeignKey objects where null=True. If the related field can't be set to None (NULL), then an object can't be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn't have null=True, this is invalid.

  4. 从相关对象集中删除所有对象: 清除()

    >>> b = Toy.objects.get(id=1)
    >>> b.box_set.clear()
    

    Note this doesn't delete the related objects -- it just disassociates them. Just like remove(), clear() is only available on ForeignKeys where null=True.


引用:Relevant Django doc on handling related objects

Django会自动在多个字段上创建反向关系,因此您可以执行以下操作:

toy = Toy.objects.get(id=toy_id)
toy.box_set.add(box)

相关问题 更多 >