Programmingjoe
Programmingjoe

Reputation: 2249

Django - Query parameter takes model type? RelatedObjectDoesNotExist: Posting has no textbook

I have installed this Django app: http://django-auditlog.readthedocs.io/en/latest/_modules/auditlog/models.html#LogEntry

The log entries are setup with two different models which are below:

class Posting(models.Model):
    textbook = models.ForeignKey(Textbook)
    condition = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to='postingpics/%Y/%m/%d', default="/textchange/nophoto.png")
    post_date = models.DateTimeField('date_posted')
    comments = models.CharField(max_length=50, default="")

    def __str__(self):
        return str(self.textbook)

    def was_posted_recently(self):
        return self.post_date >= timezone.now() - datetime.timedelta(days=1)
    was_posted_recently.admin_order_field = 'post_date'
    was_posted_recently.boolean = True
    was_posted_recently.short_description = 'Posted recently'

class Wishlist(models.Model):
    textbook = models.ForeignKey(Textbook)
    user = models.ForeignKey(User)
    wish_date = models.DateTimeField('date_wish')

    def __str__(self):
        return str(self.textbook)

    def was_wished_recently(self):
        return self.wish_date >= timezone.now() - datetime.timedelta(days=1)
    was_wished_recently.admin_order_field = 'date_wish'
    was_wished_recently.boolean = True
    was_wished_recently.short_description = 'Wished recently'


auditlog.register(Posting)
auditlog.register(Wishlist)

So in the database the model EntryLog is getting a row each time something happens to Posting or Wishlist whether that be delete, create, or update.

I am trying to complete the query below because I want to count the number of occurrences that a Posting is deleted. Separately I will do the same query for Wishlist.

LogEntry.objects.filter(action=2 , content_type=Posting).count()

content_type is of type Foreign key for the record.

When I run this query I get the error message:

RelatedObjectDoesNotExist: Posting has no textbook.

This makes me think that Posting is the wrong value to put in for content_type. Am I thinking about this correctly? Should the value for content_type be something different? I understand usually when you refer to a Foreign Key you are querying on the Foreign keys fields like Posting__condition or something like that.

Thanks in advance.

Upvotes: 0

Views: 115

Answers (1)

solarissmoke
solarissmoke

Reputation: 31434

The content_type argument should be a ContentType object, not a model class.

Instead of doing doing this manually you should use the LogEntryManagers get_for_model method:

LogEntry.objects.get_for_model(Posting).filter(action=2).count()

Upvotes: 1

Related Questions