Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8938099
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T10:32:53+00:00 2026-06-15T10:32:53+00:00

I have a model that has four fields. How do I remove duplicate objects

  • 0

I have a model that has four fields. How do I remove duplicate objects from my database?

Daniel Roseman’s answer to this question seems appropriate, but I’m not sure how to extend this to situation where there are four fields to compare per object.

Thanks,

W.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T10:32:56+00:00Added an answer on June 15, 2026 at 10:32 am
    def remove_duplicated_records(model, fields):
        """
        Removes records from `model` duplicated on `fields`
        while leaving the most recent one (biggest `id`).
        """
        duplicates = model.objects.values(*fields)
    
        # override any model specific ordering (for `.annotate()`)
        duplicates = duplicates.order_by()
    
        # group by same values of `fields`; count how many rows are the same
        duplicates = duplicates.annotate(
            max_id=models.Max("id"), count_id=models.Count("id")
        )
    
        # leave out only the ones which are actually duplicated
        duplicates = duplicates.filter(count_id__gt=1)
    
        for duplicate in duplicates:
            to_delete = model.objects.filter(**{x: duplicate[x] for x in fields})
    
            # leave out the latest duplicated record
            # you can use `Min` if you wish to leave out the first record
            to_delete = to_delete.exclude(id=duplicate["max_id"])
    
            to_delete.delete()
    

    You shouldn’t do it often. Use unique_together constraints on database instead.

    This leaves the record with the biggest id in the DB. If you want to keep the original record (first one), modify the code a bit with models.Min. You can also use completely different field, like creation date or something.

    Underlying SQL

    When annotating django ORM uses GROUP BY statement on all model fields used in the query. Thus the use of .values() method. GROUP BY will group all records having those values identical. The duplicated ones (more than one id for unique_fields) are later filtered out in HAVING statement generated by .filter() on annotated QuerySet.

    SELECT
        field_1,
        …
        field_n,
        MAX(id) as max_id,
        COUNT(id) as count_id
    FROM
        app_mymodel
    GROUP BY
        field_1,
        …
        field_n
    HAVING
        count_id > 1
    

    The duplicated records are later deleted in the for loop with an exception to the most frequent one for each group.

    Empty .order_by()

    Just to be sure, it’s always wise to add an empty .order_by() call before aggregating a QuerySet.

    The fields used for ordering the QuerySet are also included in GROUP BY statement. Empty .order_by() overrides columns declared in model’s Meta and in result they’re not included in the SQL query (e.g. default sorting by date can ruin the results).

    You might not need to override it at the current moment, but someone might add default ordering later and therefore ruin your precious delete-duplicates code not even knowing that. Yes, I’m sure you have 100% test coverage…

    Just add empty .order_by() to be safe. 😉

    https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

    Transaction

    Of course you should consider doing it all in a single transaction.

    https://docs.djangoproject.com/en/3.2/topics/db/transactions/#django.db.transaction.atomic

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have category model that has a tree structure. In my database I have
I have a model Goal that has four types of children (which all have
I have a model that has fields of name:string , default:boolean . I want
I have a model that has a ForeignKey to the built-in user model in
I have a model that has an arbitrary number of children entities. For simplicity
I have a User model that has many posts. Im trying to render the
I have a Workout model that has and belongs to many Equipment models. I
I have a parent model that has many child models, for example: App.Blog =
I have a User model that has the following default_scope: default_scope where(account_id: Account.current_account.id) If
Assume that I have a backbone model that has a bunch of boolean attributes:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.