django foreignkey不工作

时间:2018-06-11 11:47:19

标签: python django

我仍然对django foreignkey关系不满意。 下面是两个classess。

from django.db import models
from django.utils.text import slugify
from django_countries.fields import CountryField
from django.conf import settings
# Create your models here.

class PhotoGallery(models.Model):  
    title = models.CharField(max_length=255,unique=True)
    picture_choices = 
    models.CharField(max_length=255,choices=PICTURE_CHOICES,default=NTR)
    description = models.TextField(default='')
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
    on_delete=models.CASCADE,related_name='image_uploader')
    date_posted =  models.DateTimeField(auto_now=True)
    views = models.PositiveIntegerField()
    likes = models.PositiveIntegerField()
    country = CountryField(blank_label='(select country)')
    slug = models.SlugField(allow_unicode=True,unique=True)


    def __str__(self):
        return self.title


from django.contrib import admin
from gallery.models import PhotoGallery

class PhotoGalleryAdmin(admin.ModelAdmin):
     prepopulated_fields = {'slug': ('title',)}

下面是class Imagesmodel,它有一个外键。从PhotoGallery调用class Imagesmodel类不是问题。我的大问题是反向

 class ImagesModel(models.Model):
      gala_obj =
         models.ForeignKey(PhotoGallery,
         related_name='picture_gallery',on_delete=models.CASCADE) 
         post_image = models.ImageField(upload_to='gallery_pics',
                          verbose_name='Image')


   def __str__(self):
         return self.gala_obj.title

以下是我的views.py文件

    `def detailViewPage(request,slug):
          #here i wanted to get one image with the given slug 
          from `ImagesModel`
          a = get_object_or_404(PhotoGallery, slug=slug)
          selected_pic = a.picture_gallery.all()



         #here  i wanted to get all images excluding one 
         with the given slug
         object_2 = ImagesModel.objects.exclude(id=selected_pic.id)
         .order_by('-id')[:15]



         return render(request,'gallery/photogallery_detail.html',{
                                    'selected_pic':selected_pic,
                                    'object_2':object_2,
                                })`

下面是我得到的错误 enter image description here

1 个答案:

答案 0 :(得分:0)

问题不是很清楚,但我想你想要得到与对象A相关的所有图片。在你的B模型中,给你的外键一个相关的名字:

class B(models.Model):
    a = models.ForeignKey(A,related_name='post_title', related_name='pictures')
    image = models.ImageField(upload_to='gallery_pics',
                          verbose_name='Image')

在views.py中:

a = get_object_or_404(A, slug=slug)
b = a.pictures.all()

我不知道您为什么要为外键命名',但上面的代码会获得与对象A相关的所有图片。

以下内容也适用:

a = get_object_or_404(A, slug=slug)
pictures = a.b_set.all()

如果你想从对象B获取slug,那么你可以执行以下操作:

b = get_object_or_404(B, id=1)
slug = b.a.slug