[django]主次表如何取出对方数据[主表obj.子表__set()]

[sql]mysql管理手头手册,多对多sql逻辑

国家--城市例子

class Country(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name


class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

子表创建数据

City.objects.create(name='xian', country_id=1)
City.objects.create(name='xian', country_instance)

从主表取出子表的数据

1.view中取出

c = Country.objects.get(id=1)
print(c.city_set.all())

跟related_name有关系: https://www.cnblogs.com/iiiiiher/p/9542094.html

2.模板中取出

https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial03/

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

从次表取出主表的字段

方法1:
City.objects.values('name','country__name')

也可以这样
BlogArticles.objects.get(id=1).author.username
方法2:
class BlogArticles(models.Model):
    title = models.CharField(max_length=300)
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')

前端:
<small>{{ article.author.username }}</small>
原文地址:https://www.cnblogs.com/iiiiiher/p/9560240.html