django,python:AttributeError:'NoneType'对象没有属性'_meta'

时间:2015-09-24 23:10:25

标签: python django

我正在尝试测试我自己用Python编写的update_or_create方法,但是我遇到了一个错误,我用Google搜索并找不到答案。 这是源代码:

class ListingManager(models.Manager):#manage the creating/editting/deleting of listings
    def update_or_create_listing(self, listing_attributes, scraped = False, **extra_attributes):
        from sitebot.tasks import scrape_listing_url

        keys = listing_attributes.keys()
        print keys
        site = Site.objects.get(id = listing_attributes['site_id'])

        if 'sku' in keys and 'site_id' in keys and 'url' in keys:
            #create a listing if no such listing exists
            #SiteUrl.objects.get_or_create(href )
            listing, created = self.get_or_create(sku = listing_attributes['sku'], site = site, defaults = {'url': listing_attributes['url']}) 
            dynamo_db_listing_attributes = []
            if len(keys)> 3: 
                dynamo_db_listing_attributes = listing.create_or_update_attributes(listing_attributes = listing_attributes, **extra_attributes)
                if scraped == True and listing.scraped == False: #if the listing is already scraped, update the scraped status
                    listing.scraped = scraped
                    listing.save()
            if created == True and listing.scraped == False: #if the listing is just created and not scarped yet
                scrape_listing_url.delay(listing_id = str(listing.id), sku = listing.sku, listing_url = listing.url, scraper_name = listing.site.scraper.name) # what does delay do?
            return listing, listing_attributes 
        else:
            raise KeyError

这是测试代码:

class ListingManagerClassTests(TestCase):
    def setUp(self):
        #Generate Site for listing
        site = models.Site()
    #Generating Site requires ForeignKey Country
        country_for_site = models.Country() 
        country_for_site.save()
    #Generating Site requires ForeignKey Scraper
        scraper_for_site = models.Scraper() 
        scraper_for_site.scrapes_per_day = 1
        scraper_for_site.max_results = 10
        scraper_for_site.save()
        site.country = country_for_site
        site.scraper = scraper_for_site
        site.name = "siteforListingMangerTest"
        site.save()

    def test_create_listing(self):
        """update_or_create_listing should return the created listing"""
        lm = models.ListingManager()
        site = models.Site.objects.get(name="siteforListingMangerTest")
        listing_attributes = {'sku':'123456','site_id':site.id,
                              'url':'www.aaa.com'}
        #Create the new listing
        created_listing, created_listing_attributes = lm.update_or_create_listing(listing_attributes,False)
        #check if the retreived listing is the right one
        assertEqual(created_listing.sku, '123456')
        assertEqual(created_listing.site, site)
        assertEqual(created_listing.url,'www.aaa.com')

,错误是:

ERROR: test_create_listing (sitebot.tests.ListingManagerClassTests)
update_or_create_listing should return the created listing
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/wx2228/Desktop/BestBot/bestbot/sitebot/tests.py", line 35, in test_create_listing
    created_listing, created_listing_attributes = lm.update_or_create_listing(listing_attributes,False)
  File "/home/wx2228/Desktop/BestBot/bestbot/sitebot/models.py", line 90, in update_or_create_listing
    listing, created = self.get_or_create(sku = listing_attributes['sku'], site = site, defaults = {'url': listing_attributes['url']})
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 402, in get_or_create
    lookup, params = self._extract_model_params(defaults, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 457, in _extract_model_params
    for f in self.model._meta.fields:
AttributeError: 'NoneType' object has no attribute '_meta'

列表的源代码:

class Listing(models.Model):#representing the listing of an product
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    dynamoDB_connection = DynamoDBConnection(region=RegionInfo(name='us-west-2', endpoint='dynamodb.us-west-2.amazonaws.com'))
    listings_dynamo_table = Table(table_name = 'sitebot_listings', connection= dynamoDB_connection)
    sku = models.CharField(max_length=50)
    site = models.ForeignKey(Site)
    url = models.CharField(max_length=200, null = True)
    scraped = models.BooleanField(default = False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    objects = ListingManager()

3 个答案:

答案 0 :(得分:3)

实例化ListingManager直接阻止查询引擎找到底层对象。

您可以通过替换以下行来解决此问题:

lm = models.ListingManager()

使用以下行:

lm = Listing.objects

(或许)

lm = Listing.objects.all()

无论如何,您需要通过模型本身引用Manager,否则查询管理器将丢失。

它应该可以工作(我只是花了半天时间来处理类似的问题。必须爱Django魔法错误信息;)

答案 1 :(得分:1)

Python正试图在self.model中找到字段_meta。如果它说NoneType没有该属性,则意味着在您触及该行时,self.model为None。您将不得不追溯您的代码并查看为什么它的值在此时为无。

答案 2 :(得分:0)

当我重命名一个表并为其设置另一个表的外键时,这发生在我身上。

进行2次迁移,它应该可以工作;)