当前位置:  开发笔记 > 编程语言 > 正文

如何在Django中为模型获取具有反向关系的所有类的集合?

如何解决《如何在Django中为模型获取具有反向关系的所有类的集合?》经验,为你挑选了2个好方法。

鉴于:

from django.db import models

class Food(models.Model):
     """Food, by name."""
     name = models.CharField(max_length=25)

class Cat(models.Model):
     """A cat eats one type of food"""
     food = models.ForeignKey(Food)

class Cow(models.Model):
     """A cow eats one type of food"""
     food = models.ForeignKey(Food)

class Human(models.Model):
     """A human may eat lots of types of food"""
     food = models.ManyToManyField(Food)

一个人,只给出食物类,如何获得一组与"反向关系"的所有类.即给出食物类,如何获得,人类课程.

我认为这是可能的,因为Food有三个"反向关系":Food.cat_set,Food.cow_setFood.human_set.

帮助谢谢,谢谢!



1> Brian M. Hun..:

一些挖掘源代码揭示:

Django的/ DB /模型/ options.py:

def get_all_related_objects(self, local_only=False):

def get_all_related_many_to_many_objects(self, local_only=False)

并且,在上面的模型上使用这些函数,您假设得到:

>>> Food._meta.get_all_related_objects()
[,
    ,]

>>> Food._meta.get_all_related_many_to_many_objects()
[,]

# and, per django/db/models/related.py
# you can retrieve the model with
>>> Food._meta.get_all_related_objects()[0].model

注意:我听说Model._meta是'不稳定的',也许不应该在后Django-1.0世界中依赖它.

谢谢阅读.:)



2> vincent..:

A)使用多表继承并创建一个"Eater"基类,Cat,Cow和Human继承自.

B)使用通用关系,其中食物可以链接到任何其他模型.

这些是有充分记录和官方支持的功能,您最好坚持使用它们来保持自己的代码清洁,避免变通方法,并确保将来仍然支持它.

- 编辑(阿卡"如何成为一个声誉妓女")

所以,这是特定情况的配方.

让我们假设您绝对需要Cat,Cow和Human的单独模型.在实际应用程序中,您想问自己为什么"类别"字段不能完成这项工作.

通过泛型关系更容易进入"真正的"类,所以这里是B的实现.我们不能在Person,Cat或Cow中拥有'food'字段,否则我们会遇到同样的问题.所以我们将创建一个中间"FoodConsumer"模型.如果我们不想为一个实例提供多种食物,我们将不得不编写额外的验证测试.

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Food(models.Model):
     """Food, by name."""
     name = models.CharField(max_length=25)

# ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation
class ConsumedFood(models.Model):
    food = models.ForeignKey(Food, related_name="eaters")
    content_type = models.ForeignKey(ContentType, null=True)
    object_id = models.PositiveIntegerField(null=True)
    eaten_by = generic.GenericForeignKey('content_type', 'object_id')

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()
    address = models.CharField(max_length=100)
    city = models.CharField(max_length=50)
    foods = generic.GenericRelation(ConsumedFood)

class Cat(models.Model):
    name = models.CharField(max_length=50)
    foods = generic.GenericRelation(ConsumedFood)    

class Cow(models.Model):
    farmer = models.ForeignKey(Person)
    foods = generic.GenericRelation(ConsumedFood)    

现在,为了演示它,让我们写下这个工作doctest:

"""
>>> from models import *

Create some food records

>>> weed = Food(name="weed")
>>> weed.save()

>>> burger = Food(name="burger")
>>> burger.save()

>>> pet_food = Food(name="Pet food")
>>> pet_food.save()

John the farmer likes burgers

>>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12")
>>> john.save()
>>> john.foods.create(food=burger)


Wilma the cow eats weed

>>> wilma = Cow(farmer=john)
>>> wilma.save()
>>> wilma.foods.create(food=weed)


Felix the cat likes pet food

>>> felix = Cat(name="felix")
>>> felix.save()
>>> pet_food.eaters.create(eaten_by=felix)


What food john likes again ?
>>> john.foods.all()[0].food.name
u'burger'

Who's getting pet food ?
>>> living_thing = pet_food.eaters.all()[0].eaten_by
>>> isinstance(living_thing,Cow)
False
>>> isinstance(living_thing,Cat)
True

John's farm is in fire ! He looses his cow.
>>> wilma.delete()

John is a lot poorer right now
>>> john.foods.clear()
>>> john.foods.create(food=pet_food)


Who's eating pet food now ?
>>> for consumed_food in pet_food.eaters.all():
...    consumed_food.eaten_by



Get the second pet food eater
>>> living_thing = pet_food.eaters.all()[1].eaten_by

Try to find if it's a person and reveal his name
>>> if isinstance(living_thing,Person): living_thing.first_name
u'John'

"""

推荐阅读
女女的家_747
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有