简体   繁体   English

TypeError: 'ModelBase' 对象在尝试使用排除时不可迭代

[英]TypeError: 'ModelBase' object is not iterable when trying to use Exclude

I have the following two models:我有以下两个模型:

class Listings(models.Model):
    CATEGORY = [
    ("Miscellaneous", "Miscellaneous"),
    ("Movies and Television", "Movies and Television"),
    ("Sports", "Sports"),
    ("Arts and Crafts", "Arts and Crafts"),
    ("Clothing", "Clothing"),
    ("Books", "Books"),
]
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=500)
    bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
    image = models.URLField(null=True, blank=True)
    category = models.CharField(max_length=64, choices=CATEGORY, default=None)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")

class CloseListing(models.Model):
    listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")

I want to be able to query through all the objects of every listing that is not in the CloseListing model.我希望能够查询不在 CloseListing 模型中的每个列表的所有对象。 How can I do this?我怎样才能做到这一点?

I tried the code in the answer, and I am still not able to query through all the objects of every listing not in the CloseListing model.我尝试了答案中的代码,但仍然无法查询不在 CloseListing 模型中的每个列表的所有对象。 I think it might have to do with how I am saving the model.我认为这可能与我如何保存模型有关。 The following code is the part of the view that deals with the CloseListing model.以下代码是处理 CloseListing 模型的视图部分。

def index(request):
    listings = Listings.objects.all().exclude(id__in=CloseListing)
    return render(request, "auctions/index.html",{
        "listings": Listings.objects.all()
    })

error message: TypeError: 'ModelBase' object is not iterable because of listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") .错误消息: TypeError: 'ModelBase' object is not iterable because listings = models.ForeignKey(Listings, on_delete=models.CASCADE, default="")

closeListing part of views.py closeListing 部分views.py

@login_required(login_url='login')
def listing(request, id):
    #gets listing
    listing = get_object_or_404(Listings.objects, pk=id)
    sellar = listing.user

    #close listing code
    if sellar == request.user:
        closeListingButton = True
    else: 
        closeListingButton = False
    closeListing = ''
    try:
        has_closed = get_list_or_404(CloseListing, Q(
            user=request.user) & Q(listings=listing))
    except:
        has_closed = False
    if has_closed:
        closeListing = False
    else: 
        closeListing = True

   if request.method == "POST":
       #close listing code
        if request.POST.get('close'):
          CloseListing.objects.create(user=request.user,
 listings=listing)
            closeListing = True
            closeListingButton = False
            add_or_remove_watchlist = True
            winning_bid = Bids.objects.aggregate(Max('bid'))
            winning_bid = Bids.objects.latest('bid')
            winner = winning_bid.user
            return render(request, "auctions/listing.html",{
                        "auction_listing": listing,
                        "comments": comment_obj,
                        "bids": bid_obj,
                        "closeListingButton": closeListingButton,
                        "closeListing": closeListing,
                        "closedMessage": "This listing is closed.",
                        "winner": winner
            })
            return render(request, "auctions/listing.html",{
                 "auction_listing": listing,
                 "closeListingButton": closeListingButton, 
                 "closeListing": closeListing
            })

You should not query directly through model, which is CloseListing , you can first filter all close listings from CloseListing model then exclude all those listings which are in CloseListing by exclude() .您不应该直接通过模型进行查询,即CloseListing ,您可以先从CloseListing模型中过滤所有关闭列表,然后通过exclude()排除所有在CloseListing中的列表。

views.py视图.py

def index(request):
    close_listings = CloseListing.objects.values('listings')
    listings=Listings.objects.exclude(id__in=close_listings)
    return render(request, "auctions/index.html",{
        "listings": listings
    })

I'd recommend you to add __str__ in Listing model as:我建议您在Listing模型中添加__str__为:

class Listings(models.Model):
    CATEGORY = [
        ("Miscellaneous", "Miscellaneous"),
        ("Movies and Television", "Movies and Television"),
        ("Sports", "Sports"),
        ("Arts and Crafts", "Arts and Crafts"),
        ("Clothing", "Clothing"),
        ("Books", "Books"),
    ]
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=500)
    bid = models.DecimalField(max_digits=1000000000000, decimal_places=2)
    image = models.URLField(null=True, blank=True)
    category = models.CharField(max_length=64, choices=CATEGORY, default=None)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")

    def __str__(self) -> str:
        return f'{self.title}'

By adding __str__ you would see instances title instead of objects.通过添加__str__您将看到实例标题而不是对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django TypeError:“ ModelBase”对象不可迭代 - Django TypeError: 'ModelBase' object is not iterable TypeError:“ ModelBase不可迭代” - TypeError: “ModelBase is not iterable” TypeError: int object 在尝试使用素数列表时不可迭代 - TypeError: int object is not iterable when trying to use a list of prime numbers 当我尝试在python中使用getpixel()时,“TypeError:'int'对象不可迭代” - “TypeError: 'int' object is not iterable” when I was trying to use getpixel() in python TypeError:尝试使用列表推导时无法解压缩不可迭代的int对象 - TypeError: cannot unpack non-iterable int object when trying to use list comprehension 尝试使用whisper-merge时,获取错误“TypeError:'NoneType'对象不可迭代” - Getting the error “TypeError: 'NoneType' object is not iterable” when trying to use whisper-merge 尝试比较列表时获取“ TypeError:'int'对象不可迭代” - Getting “TypeError: 'int' object is not iterable” when trying compare list 尝试返回布尔值时,TypeError(“'bool'对象不可迭代”,) - TypeError(“'bool' object is not iterable”,) when trying to return a Boolean TypeError:尝试创建2个子图时,'AxesSubplot'对象不可迭代 - TypeError: 'AxesSubplot' object is not iterable when trying to create 2 subplots TypeError:尝试在python中反转字典时,'int'对象不可迭代 - TypeError: 'int' object is not iterable when trying to reverse a dictionary in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM