【问题标题】:How do you get a field related by OneToOneField and ManyToManyField in Django?如何在 Django 中获取 OneToOneField 和 ManyToManyField 相关的字段?
【发布时间】:2016-12-21 01:53:37
【问题描述】:
如何在 Django 中获取 OneToOneField 和 ManyToManyField 相关的字段?
例如,
class A(models.Model):
myfield = models.CharField()
as = models.ManyToManyField('self')
class B(models.Model):
a = models.OneToOneField(A)
如果我想使用 B 类获取一个 'myfield' 和所有关联的 'as',给定一个 'myfield' 等于像 'example' 这样的字符串,它是如何完成的?
【问题讨论】:
标签:
python
django
django-models
django-orm
【解决方案1】:
Models.py
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self): # __unicode__ on Python 2
return "%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self): # __unicode__ on Python 2
return "%s the restaurant" % self.place.name
让我们创建一个地点实例。
p1 = Place.objects.create(name='Demon Dogs', address='944 W. Fullerton')
然后创建一个餐厅对象。
r = Restaurant.objects.create(place=p1, serves_hot_dogs=True, serves_pizza=False)
现在,从餐厅进入地点:
>>> r.place
<Place: Demon Dogs the place>
反之亦然从地方访问餐厅
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
多对多字段部分没看懂,能详细说明一下吗?
【解决方案2】:
首先你得到一个B的实例b,你可以通过b的a属性轻松访问myfield和as
b.a.myfield
b.a.as.all()
此外,CharField 需要一个 max_length 属性,如下所示:
class A(models.Model):
myfield = models.CharField(max_length=128)
as = models.ManyToManyField('self')
class B(models.Model):
a = models.OneToOneField(A)
一般来说,给你的模型及其属性提供更具描述性的名称,或者至少添加 cmets 来解释这些模型所代表的含义